8

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?

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78

2 Answers2

12

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?
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
  • It's worth noting that `join` blocks the calling thread until the thread's been terminated properly. – tadman Mar 26 '18 at 15:56
1

I'm doing this:

thread = Thread.new { loop {} }
thread.kill
sleep 0.001 while thread.alive?

This is how I terminate threads in my ThreadPool.

yegor256
  • 102,010
  • 123
  • 446
  • 597