Geo*_*Geo 29 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
Run Code Online (Sandbox Code Playgroud)
我需要做什么才能获得进程命令的输出?我怎么能创建一个自定义线程,以便我可以完成这个?
Vin*_*jip 46
剧本
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
Run Code Online (Sandbox Code Playgroud)
说明如何实现您的需求.它的好处是保持输出与生成它的线程,因此您可以随时加入并获取每个线程的输出.运行时,脚本打印
Hi from thread #1 Hi from thread #2 Hi from thread #3 Hi from thread #4 Hi from thread #5
ihe*_*gie 31
我发现使用collect将Threads收集到列表中更简单,并使用thread.value连接并返回线程中的值 - 这会将其修剪为:
#!/usr/bin/env ruby
threads = (1..5).collect do |i|
Thread.new { `echo Hi from thread ##{i}` }
end
threads.each do |t|
puts t.value
end
Run Code Online (Sandbox Code Playgroud)
运行时,会产生:
Hi from thread #1
Hi from thread #2
Hi from thread #3
Hi from thread #4
Hi from thread #5
Run Code Online (Sandbox Code Playgroud)
Oto*_*lez 12
这是一种使用#value()和#join()从线程数组中检索值的简单而有趣的方法.
a, b, c = [
Thread.new { "something" },
Thread.new { "something else" },
Thread.new { "what?" }
].map(&:value)
a # => "something"
b # => "something else"
c # => "what?"
Run Code Online (Sandbox Code Playgroud)