Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
Aaron Christiansen Avatar asked Mar 26 '18 11:03

Aaron Christiansen


People also ask

How do you stop a thread in Ruby?

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 .

What does thread join do in Ruby?

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.

What is mutex in Ruby?

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.

Does Ruby have real threads?

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.


2 Answers

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?
like image 199
Aaron Christiansen Avatar answered Sep 29 '22 01:09

Aaron Christiansen


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.

like image 42
yegor256 Avatar answered Sep 29 '22 00:09

yegor256