jmwright
jmwright

Reputation: 131

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

Upvotes: 5

Views: 975

Answers (1)

Bjoern Rennhak
Bjoern Rennhak

Reputation: 6936

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?

Upvotes: 1

Related Questions