Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 like to get the output of the process command now. end 

What do I have to do to get the output of the process command? How could I create a custom thread so that I can accomplish this?

like image 393
Geo Avatar asked Sep 05 '09 14:09

Geo


People also ask

How do you return a value from a thread?

How to Return Values From a Thread. A thread cannot return values directly. The start() method on a thread calls the run() method of the thread that executes our code in a new thread of execution. The run() method in turn may call a target function, if configured.

Which function is used to return a value from the thread back?

The function foo below returns a string 'foo' .

Is Ruby single threaded or multithreaded?

The Ruby Interpreter is single threaded, which is to say that several of its methods are not thread safe. In the Rails world, this single-thread has mostly been pushed to the server.

Can a thread return a value C#?

Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke .


2 Answers

The script

threads = [] (1..5).each do |i|   threads << Thread.new { Thread.current[:output] = `echo Hi from thread ##{i}` } end threads.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 #1 Hi from thread #2 Hi from thread #3 Hi from thread #4 Hi from thread #5 
like image 64
Vinay Sajip Avatar answered Oct 01 '22 13:10

Vinay Sajip


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 
like image 23
iheggie Avatar answered Oct 01 '22 13:10

iheggie