Ruby 如何在多线程中获取每个线程的返回值

saitubao · July 11, 2014 · Last by saitubao replied at July 12, 2014 · 2605 hits

我想获取每个线程的返回值(比如是一个 hash),该怎么操作呢?

写到存储里,比如 mongo/redis

这样可以么?

thr = Thread.new { Thread.current[:return] = "some hash" }
thr.join
thr[:return] # some hash

轻量点的还可以用 queue,工作线程把结果放到 queue 里,收集的线程去取,没内容的话,收集的线程会 blocking。

http://ruby-doc.org/stdlib-2.0.0/libdoc/thread/rdoc/Queue.html

result = []
threads = []
5.times do |num|
  threads << Thread.new{
    result << {Thread.current.object_id.to_s => num}
  }
end
threads.each {|thread| thread.join}
p result

输出

[{"69885727586360"=>0}, {"69885727586220"=>1}, {"69885727586080"=>2}, {"69885727585620"=>3}, {"69885727585480"=>4}]

谢谢给位大虾了!

You need to Sign in before reply, if you don't have an account, please Sign up first.