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 に答える