views:

74

answers:

2

Is the following inefficient? I want to allocate nearly all resources to threads but I'm wondering if in this case this loop will consume a lot of CPU time.

Thanks!

threads = create_threads #method that returns an Array of Threads
loop do
  alive = false
  threads.each do |thread|
    if thread.alive?
      alive = true
    end
  end
  break unless alive
end
+1  A: 
threads.each do |thread|
  thread.join
end
Farrel
But that defeats multi-threading as concurrency is effectively disabled. I still want Ruby to switch between the main thread, thread 1, thread 2, etc
Alexandre
It still switches between the threads, it jut waits until they're all finished before continuing. If thread1 is long running and thread2 isn't and we're waiting on a join on thread1, thread2 will continue to execute and finish. When thread1 is finished we'll call join on thread2 which will immediately return.
Farrel
Hi Farrel,You're right, the other threads continue to execute. This example clarified it for me.http://pastebin.org/90678
Alexandre
+1  A: 
threads.each &:join

my_thread.join returns as soon as my_thread exits.

Kay Sarraute