views:

249

answers:

2

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?

A: 

You should use the Queue class. Each thread should put its result in the queue, and the main thread should fetch it from there. Notice that using that approach, results my be in a order different from thread creation order in the queue.

Martin v. Löwis
+4  A: 

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
Vinay Sajip
Vinay, maybe you can have a look at this too: http://stackoverflow.com/questions/1383470/why-is-this-running-like-it-isnt-threaded
Geo