如何从Ruby中的线程返回值? [英] How can I return a value from a thread in Ruby?

查看:119
本文介绍了如何从Ruby中的线程返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

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命令的输出?我该如何创建一个自定义线程来完成此任务?

What do I have to do to get the output of the process command? How could I create a custom thread so that I can accomplish this?

推荐答案

脚本

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

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

illustrates how to accomplish what you need. It has the benefit of keeping the output with the thread that generated it, so you can join and get the output of each thread at any time. When run, the script prints


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

这篇关于如何从Ruby中的线程返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆