How do I manage ruby threads so they finish all their work?
In ruby 1.9 (and 2.0), you can use ThreadsWait
from the stdlib for this purpose:
require 'thread'require 'thwait'threads = []threads << Thread.new { }threads << Thread.new { }ThreadsWait.all_waits(*threads)
If you modify spawn_thread_for
to save a reference to your created Thread
, then you can call Thread#join
on the thread to wait for completion:
x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }x.join # Let the threads finish beforea.join # main thread exits...
produces:
abxyzc
(Stolen from the ri Thread.new
documentation. See the ri Thread.join
documentation for some more details.)
So, if you amend spawn_thread_for
to save the Thread references, you can join on them all:
(Untested, but ought to give the flavor)
# main threadwork_units = Queue.new # and fill the queue...threads = []10.downto(1) do threads << Thread.new do loop do w = work_units.pop Thread::exit() if w.nil? do_some_work(w) end endend# main thread continues while work threads devour workthreads.each(&:join)