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

saitubao · 2014年07月11日 · 最后由 saitubao 回复于 2014年07月12日 · 2605 次阅读

我想获取每个线程的返回值(比如是一个 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}]

谢谢给位大虾了!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号