Home > database >  Why does Thread#kill prevent new threads from being created and fail silently in Ruby?
Why does Thread#kill prevent new threads from being created and fail silently in Ruby?

Time:06-30

After killing a thread, creating new threads seems to fail silently.

thread = Thread.new { sleep 1; puts :ok }
sleep 2
thread = Thread.new { sleep 1; puts :ok }
sleep 2

puts "#2"

thread = Thread.new { sleep 1; puts :ok }
thread.kill
thread = Thread.new { sleep 1; puts :ok }
sleep 2

Output:

ok
ok
#2
ok

Last thread fails silently.

How to kill a thread and create a new one?

Tested on ruby 2.6.8p205 and ruby 3.1.0p0

CodePudding user response:

Last thread fails silently.

You're drawing the wrong conclusion, it's the thread before that doesn't generate output. It becomes obvious if you print different values:

thread = Thread.new { sleep 1; puts 'ok #1' }
sleep 2
thread = Thread.new { sleep 1; puts 'ok #2' }
sleep 2

puts "-----"

thread = Thread.new { sleep 1; puts 'ok #3' }
thread.kill
thread = Thread.new { sleep 1; puts 'ok #4' }
sleep 2

Output:

ok #1
ok #2
-----
ok #4

How to kill a thread and create a new one?

You exactly did that. The penultimate thread instance gets killed via thread.kill while it is sleeping (maybe even before). The last thread instance works as usual. There's no failure in your code.

  • Related