2012-09-18 117 views
1

我想要多个线程同时触发所有的线程。在ruby中同步线程

10.times do 
    Thread.new do 
    sleep rand(5)    # Initialize all the stuff 
    wait_for_all_other_threads # Wait for other threads to initialize their stuff 
    fire!      # Go. 
    end 
end 

我将如何实现wait_for_all_other_threads所以他们都fire!在同一时间?

回答

0
require "thread" 

N = 100 

qs = (0..1).map { Queue.new } 

t = 
    Thread.new(N) do |n| 
    n.times { qs[0].pop } 
    n.times { qs[1].push "" } 
    end 

ts = 
    (0..N-1).map do |i| 
    Thread.new do 
     sleep rand(5) # Initialize all the stuff 
     STDERR.puts "Init: #{i}" 
     qs[0].push "" 
     qs[1].pop  # Wait for other threads to initialize their stuff 
     STDERR.puts "Go: #{i}"  # Go. 
    end 
    end 
[t, *ts].map(&:join) 
+0

的OP希望所有的工作线程暂停,并在更多或更少的疏通的同时,也就是在同一个事件,只有* *后,他们都被初始化。这段代码取消了一个独立于所有其他工作者的工作者线程,而不是OP想要的东西。 – pilcrow

+0

@pilcrow谢谢你指出这一点,我完全错过了它。看起来像一个队列是不够的。编辑答案。 –