Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I've started a thread with the following code, how can I trap/detect the exit call from within the thread itself so I can do some clean-up before it terminates?

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

I was thinking that maybe it would 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
like image 302
jmwright Avatar asked Nov 12 '22 09:11

jmwright


1 Answers

This is untested, but Thread like everything can by specialized by just jumping in before the GC gets active. So I think you can add a ObjectSpace finalizer method which is executed just before Thread is garbage collected to do what you want.

Ruby: Destructors?

like image 107
Bjoern Rennhak Avatar answered Nov 15 '22 06:11

Bjoern Rennhak