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

2 Answers 2

3
threads.each &:join

my_thread.join returns as soon as my_thread exits.

2
threads.each do |thread|
  thread.join
end
3
  • 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
    Feb 12, 2010 at 2:34
  • 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
    Feb 12, 2010 at 5:58
  • Hi Farrel, You're right, the other threads continue to execute. This example clarified it for me. pastebin.org/90678
    – Alexandre
    Feb 12, 2010 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.