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
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?
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