justapilgrim
justapilgrim

Reputation: 6882

How to wait only for the first thread in an array to finish in Ruby?

In Ruby, to wait every thread in an array to finish its work can be done using Thread#join:

threads = []

threads << Thread.new { sleep 1 }
threads << Thread.new { sleep 5 }
threads << Thread.new { sleep 2 }

# waiting for all work to finish
threads.each(&:join)

But what I need to do, is to wait only for the first thread of the array to finish. Once the first is done, I want to stop the execution.

Is there a easy way or built-in way to do so in Ruby?

Upvotes: 1

Views: 377

Answers (1)

matthewd
matthewd

Reputation: 4435

For a thread-safe way to wait for something to happen in one of several threads, you can use a Queue.

queue = Queue.new
threads = []

threads << Thread.new { sleep 2; queue.push(nil) }
threads << Thread.new { sleep 50; queue.push(nil) }
threads << Thread.new { sleep 20; queue.push(nil) }

# wait for one
queue.pop

# clean up the rest
threads.each(&:kill).each(&:join)

Upvotes: 6

Related Questions