4
如果我使用以下代碼啓動線程,如何捕獲/檢測線程本身內的退出調用,以便我可以進行一些清理它終止之前?如何檢測線程中的Ruby線程何時死亡
thr = Thread.new { sleep }
thr.status # => "sleep"
thr.exit
thr.status # => false
我在想,也許它會像下面這樣,但我不確定。
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
你不能。線程#停止是一個無法消除的大錘。如果您想通過清理來發信號終止或取消,則需要使用更微妙的方法。 – Linuxios 2013-03-15 21:23:10