at.
at.

Reputation: 52580

Easiest way to make sure a lot of threads finish in Ruby?

I'm creating a lot of threads:

(1..255).each do |n|
  Thread.new do
    sleep(10) # does a lot of work
  end
end
# at this point I need to make sure all the threads completed

I would've hoped I could add each thread to a ThreadGroup and call a function like wait_until_all_threads_complete on that ThreadGroup. But I don't see anything obvious in the Ruby docs.

Do I have to add each thread to an array and then iterate over each one calling thread.join? There must be an easier way for such an extremely common use case.

threads = (1..255).map do |n|
  Thread.new do
    sleep(10) # does a lot of work
  end
end
threads.each do |thread|
  thread.join
end

Upvotes: 0

Views: 158

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84443

Use ThreadGroup#list

If you assign threads to a ThreadGroup with ThreadGroup#add, you can map Thread#join or other Thread methods onto each member of the group as returned by the ThreadGroup#list method. For example:

thread_group = ThreadGroup.new
255.times do
  thread_group.add Thread.new { sleep 10 }
end
thread_group.list.map &:join

This will only join threads belonging to thread_group, rather than to ThreadGroup::Default.

Upvotes: 2

Related Questions