如果我有以下代码:
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/