How can I return a value from a thread in Ruby?

后端 未结 5 1111
清歌不尽
清歌不尽 2021-02-03 19:08

If I have the following code :

threads = []
(1..5).each do |i|
  threads << Thread.new { `process x#{i}.bin` } 
end
threads.each do |t|
  t.join
  # i\'d l         


        
5条回答
  •  走了就别回头了
    2021-02-03 19:53

    This is a simple, and interesting way to use Thread#value:

    a, b, c = [
      Thread.new { "something" },
      Thread.new { "something else" },
      Thread.new { "what?" }
    ].map(&:value)
    
    a # => "something"
    b # => "something else"
    c # => "what?"
    

提交回复
热议问题