在ruby中同步线程

时间:2012-09-18 13:36:11

标签: ruby multithreading

我想要同时激活多个线程。

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!

2 个答案:

答案 0 :(得分:2)

使用障碍同步:http://rubygems.org/gems/barrier/

对barrier的调用将导致每个线程都被阻塞,直到所有线程都调用它为止。

答案 1 :(得分: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)