如果我有以下代码:
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命令的输出?我怎样才能创建一个自定义线程来完成这个任务呢?
如果我有以下代码:
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