iblue
iblue

Reputation: 30434

Synchronize threads in ruby

I want multiple threads to all fire at the same time.

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

How would I implement wait_for_all_other_threads so they all fire! at the same time?

Upvotes: 1

Views: 371

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

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)

Upvotes: 1

Brady
Brady

Reputation: 10357

Use a barrier sync: http://rubygems.org/gems/barrier/

A call to barrier will cause each thread to block until all of the threads have called it.

Upvotes: 2

Related Questions