Robert Klemme
12/31/2007 3:07:00 PM
On 31.12.2007 06:45, Skye Shaw!@#$ wrote:
> On Dec 30, 9:02 pm, thefed <fed...@gmail.com> wrote:
>> Take this code from the Ruby Cookbook:
>>
>> module Enumerable
>> def each_simultaneously
>> threads = []
>> each { |e| threads << Thread.new { yield e } }
>> return threads
>> end
>> end
>>
>> It is used on an array so that you may do this:
>> [1,2,3].each_simultaneously do |i|
>> sleep 5
>> puts i
>> end
>>
>> And it works!
>
>
> What did you expect to happen?
> The example you provided will do nothing but create threads and
> exit.
>
>> But why don't I need to call threads.each {|t| t.join }?
>
> Any running threads are killed when the program exits.
>
>
>> And if I did, would it slow it down?
>
> Generally speaking, the only thing it would slow down (stop really) is
> the execution path of the main thread.
>
> Now if for some reason your main thread has to do other work, a join
> would delay that, of course.
Nevertheless it's good practice to join. If main has other work to do
then you should join once that is done, i.e. at the end of the script.
If those threads have terminated already you basically only have the
overhead of the Threads Array iteration - but you get robustness in
return, i.e. you ensure that all those Threads can terminate properly
(assuming that they are written in a way to do that eventually).
Kind regards
robert