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

后端 未结 5 1174
清歌不尽
清歌不尽 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:39

    I found it simpler to use collect to collect the Threads into a list, and use thread.value to join and return the value from the thread - this trims it down to:

    #!/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
    

    When run, this produces:

    Hi from thread #1
    Hi from thread #2
    Hi from thread #3
    Hi from thread #4
    Hi from thread #5
    

提交回复
热议问题