ruby - 如何只等待数组中的第一个线程在 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 中有简单的方法或内置的方法吗?
解决方案
对于等待多个线程之一中发生某些事情的线程安全方式,您可以使用队列。
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)
推荐阅读
- javascript - DOM 元素检索产生不一致的数据
- tomcat - Spring Boot 启动失败
- c# - 使用实体框架查询数据库未按预期工作
- python - 按 ID 和时间透视具有混合值类型的 pandas 表
- reactjs - react-google-maps StandaloneSearchBox 卸载
- r - R / DESeq中值的行名
- c# - ASP.NET MVC 中请求正文的 XML 反序列化
- angular - Angular 接口出现未定义
- bi-publisher - 输出为 excel 时 .xpt 报告的 BiPublisher 表名称
- node.js - IBM Cloud Object Storage, cannot modify object ACL permissions