How to detect when a Ruby thread is killed from a thread

If I started a thread with the following code, how can I capture / detect an exit call from the thread itself so that I can do some cleanup before it finishes?

thr = Thread.new { sleep } thr.status # => "sleep" thr.exit thr.status # => false 

I thought it might be something like the following, but I'm not sure.

 thr = Thread.new { begin sleep rescue StandardError => ex puts ex.message rescue SystemExit, Interrupt puts 'quit' ensure puts 'quit' end } thr.status # => "sleep" thr.exit #=> "quit" thr.status # => false 
+4
source share
1 answer

This has not been verified, but Thread, like everyone else, can specialize by simply jumping before the GC activates. So I think you can add the finalizer ObjectSpace method, which runs just before Thread collects the garbage to do what you want.

Ruby: Destructors?

0
source

All Articles