1

我希望多个线程同时触发。

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!同时进行?

4

2 回答 2

2

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

对屏障的调用将导致每个线程阻塞,直到所有线程都调用它。

于 2012-09-18T13:37:49.857 回答
1
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)
于 2012-09-18T14:43:00.803 回答