How can I return a value from a thread in Ruby?
The script
threads = [](1..5).each do |i| threads << Thread.new { Thread.current[:output] = `echo Hi from thread ##{i}` }endthreads.each do |t| t.join puts t[:output]end
illustrates how to accomplish what you need. It has the benefit of keeping the output with the thread that generated it, so you can join and get the output of each thread at any time. When run, the script prints
Hi from thread #1Hi from thread #2Hi from thread #3Hi from thread #4Hi from thread #5
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 rubythreads = (1..5).collect do |i| Thread.new { `echo Hi from thread ##{i}` }endthreads.each do |t| puts t.valueend
When run, this produces:
Hi from thread #1Hi from thread #2Hi from thread #3Hi from thread #4Hi from thread #5
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?"