rubymultithreadingruby-2.4ruby-2.5

Wait for a thread to die in Ruby


It appears that, in Ruby 2.4 and 2.5, threads don't die as soon as you invoke #kill on them. This code snippet will print Not dead a few times:

thread = Thread.new { loop {} }
thread.kill
puts "Not dead" while thread.alive?

I'd like to block execution of the main thread until the secondary thread is killed. I tried using thread.join.kill, but of course this blocks the main thread because the thread's loop never terminates.

How can I ensure that a thread is killed before the main thread continues?


Solution

  • Figured it out; you can still #join the thread after killing it, so you can use thread.kill.join to block until the thread dies.

    This code never prints Not dead:

    thread = Thread.new { loop {} }
    thread.kill.join
    puts "Not dead" while thread.alive?