2014-09-22 146 views
1

我有類似下面前完成:如何等待所有線程執行的下一行

all_hosts.each do |hostname| 
    Thread.new { 
    ... 
    } 
end 
# next line of execution 

主機的每個上述打開自己的線程和執行的命令。我希望等待所有線程完成執行,然後再移至文件的下一部分。有沒有一個簡單的方法來做到這一點?

回答

4

使用Thread#join將等待線程終止。

要做到這一點,你需要保存線程;所以用map代替each

threads = all_hosts.map do |hostname| 
    Thread.new { 
    # commands 
    } 
end 

threads.each(&:join) 
2

Thread documentation解釋它:

或者,您也可以使用數組在下面的例子中一次處理多個線程,如:

threads = [] 
threads << Thread.new { puts "Whats the big deal" } 
threads << Thread.new { 3.times { puts "Threads are fun!" } } 

創建幾個線程,我們等待後他們都連續完成。

threads.each { |thr| thr.join } 

應用到你的代碼:

threads = [] 

all_hosts.each do |hostname| 
    threads << Thread.new { ... } 
end 

threads.each(&:join) 

# next line of execution