1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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) 

2 Comments

The OP wants all worker threads to pause and unblock at more-or-less the same time, that is, upon the same event, and only after they are all initialized. This snippet instead unblocks a worker thread independent of all other workers — not what the OP wants.
@pilcrow Thanks for pointing this out, I completely missed it. Looks like one queue is not enough. Edited answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.