I’m reading the pickaxe and it says on p137 “When a Ruby program
terminates, all threads are killed, regardless of their states.
However, you can wait for a particular thread to finish by calling
that thread’s Thread#join method. The calling thread will block until
the given thread is finished.”
I wrote a small program to see if I understood how this works.
running = true
t = Thread.new do
print “Thread started\n”
print “Thread finished\n”
puts “After join”
running = false
puts “Program finished”
The paragraph I quoted makes me think that it should print “Thread
started…After join…Thread finished…Program finished” It joins
the thread and continues processing, setting running to false, which
causes the thread’s loop to end. Also not that it could say “Program
finished…Thread finished”, I don’t think there’s a way to know for
Anyway, as you might guess, the actual output is “Thread started” and
it just hangs. I checked out the docs
(http://www.ruby-doc.org/core/classes/Thread.html#M001469) and it says
“Does not return until thr exits or until limit seconds have passed.”
That explains why it’s hanging - join is waiting for the thread to
exit. I’m confused as to the usefulness of threads in Ruby then. I
can see that if I were to create 5 threads, I can have them running
all at the same time, and then resume normal program execution.
However, more often I’d like to just perform some task in the
background while my program carries on as normal. In that case, a
Thread (to the extent that I know how to use it) is nothing more than
a method call.
Finally, I’ve tried putting Thread.pass inside the loop. Common sense
tells me it won’t work because join still hasn’t returned, but perhaps
Thread.pass is the answer if I’m not even supposed to be calling #join
in the first place.
I’d really appreciate some help in understanding this, and some
direction as to how to execute a task in the background.