首页 > 解决方案 > 如何只等待数组中的第一个线程在 Ruby 中完成?

问题描述

在 Ruby 中,要等待数组中的每个线程完成其工作,可以使用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)

但我需要做的是只等待数组的第一个线程完成。一旦第一个完成,我想停止执行。

在 Ruby 中有简单的方法或内置的方法吗?

标签: rubymultithreading

解决方案


对于等待多个线程之一中发生某些事情的线程安全方式,您可以使用队列。

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)

推荐阅读