如何检测Ruby线程何时从线程中被杀死

jmw*_*ght 5 ruby multithreading

如果我使用以下代码启动了一个线程,如何从线程本身中捕获/检测退出调用,以便在终止之前进行一些清理?

thr = Thread.new { sleep }
thr.status # => "sleep"
thr.exit
thr.status # => false
Run Code Online (Sandbox Code Playgroud)

我在想,也许它会像下面这样,但我不确定.

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
Run Code Online (Sandbox Code Playgroud)

Bjo*_*hak 1

这是未经测试的,但是像所有线程一样,可以通过在 GC 激活之前跳入来进行专门化。因此,我认为您可以添加一个 ObjectSpace 终结器方法,该方法在 Thread 被垃圾收集之前执行,以执行您想要的操作。

鲁比:析构函数?