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?
For terminating threads, Ruby provides a variety of ways to do this. Alternatively, you can use the instance method exit , or any of its aliases kill or terminate .
Calling Thread. join blocks the current (main) thread. However not calling join results in all spawned threads to be killed when the main thread exits.
Mutex is a class that implements a simple semaphore lock for mutually exclusive access to some shared resource. That is, only one thread may hold the lock at a given time.
Since Threads are actually implemented in Ruby, they can, like any other Ruby object, be serialized and sent to a different VM in a different POSIX Thread.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With