Wait for a thread to die in Ruby
Asked Answered
W

2

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?

Winou answered 26/3, 2018 at 11:23 Comment(0)
W
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?
Winou answered 26/3, 2018 at 11:25 Comment(1)
It's worth noting that join blocks the calling thread until the thread's been terminated properly.Chaos
R
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.

Raddy answered 8/1, 2019 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.