ruby - 如何从 Ruby 中的线程返回值?

标签 ruby multithreading

如果我有以下代码:

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

我必须做什么才能获得进程命令的输出?我如何创建自定义线程才能完成此任务?

最佳答案

脚本

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 中的线程返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1383390/

相关文章:

ruby - 如何获取 Ruby 上的特定操作系统版本?

ruby - 通过数组的API请求

c++ - 设计线程安全类时避免嵌套调用时的死锁

multithreading - 协程如何比线程更快?

Python GUI 多处理并且仍然卡住

ruby - 新的 Ruby 1.9 哈希语法

ruby-on-rails - Rails 中的通知系统

ruby - 如何从 Ruby 函数返回值以用于程序的其余部分

c - 批量处理

vb.net - 使用事件从具有另一个类的后台工作人员更新 UI