From: Ken Bloom Date: 2008-01-01T02:39:58+09:00 Subject: Re: Why not call Thread.join? On Mon, 31 Dec 2007 00:02:10 -0500, thefed 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 When I ran this (not in IRB) it didn't work. The interpreter terminated before any of the threads finished sleeping for 5 seconds. In any case, you want to join each thread so that the next statement will only execute after all of the threads have finished their work (otherwise your next statement will see an undetermined intermediate view of the array). > OK, I understand it better. But why does each {|t| t.join} join them > all at the same time (ish), and not wait for the first one to finish > executing before joining the others? It joins them one at a time in order. But while your main thread is waiting for a specific thread to finish, any other thread is also allowed to execute, and possibly terminate. If thread b terminates while thread a is joined, then you call join on thread b, join will return immediately since there's nothing to wait for. Hence, each{|t| t.join} finishes practically immediately when the longest running thread finishes. --Ken -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/