如果我有以下代码:

threads = []
(1..5).each do |i|
  threads << Thread.new { `process x#{i}.bin` } 
end
threads.each do |t|
  t.join
  # i'd like to get the output of the process command now.
end

我需要做什么才能获得process命令的输出?我怎样才能创建一个自定义线程来完成这个任务呢?

推荐答案

playbook

threads = []
(1..5).each do |i|
  threads << Thread.new { Thread.current[:output] = `echo Hi from thread ##{i}` }
end
threads.each do |t|
  t.join
  puts t[:output]
end

说明如何完成你需要的.它的好处是将输出与生成它的线程保持在一起,因此您可以随时加入并获取每个线程的输出.运行时,脚本会打印

Hi from thread #1
Hi from thread #2
Hi from thread #3
Hi from thread #4
Hi from thread #5

Ruby相关问答推荐

如何在 Ruby 中为链表实现#pop

Ruby:这两种混入模块方法是否等效?

当 node 名称是/包含整数时,使用 Nokogiri 解析非 XML 文档

如何使用正则表达式在字符串中查找特定匹配项

Rack并发 - rack.multithread、async.callback 或两者兼而有之?

ActiveRecord::AdapterNotSpecified 数据库配置未指定适配器

何时在 Ruby 方法中使用 `self.foo` 而不是 `foo`

判断Ruby中的目录是否为空

检测 ruby​​ 是否在 Windows 上运行的正确方法是什么?

从href html标签中提取带有Ruby中nokogiri的链接(URL)?

Ruby 中的发送方法

try 学习/理解 Ruby 的 setter 和 getter 方法

如何自定义 Jekyll 的 url?

在 Rails 中,如何向 String 类添加新方法?

ruby module_function 与包含模块

使用 `?`(问号)在 Ruby 中获取 ASCII 字符代码失败

Ruby - 用另一个字符串替换第一次出现的子字符串

要散列的散列数组

如何在不为 RVM 用户授予 sudo 访问权限的情况下安装 RVM 系统要求

查找与给定条件匹配的元素的索引