2013-03-15 92 views
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 
+4

你不能。線程#停止是一個無法消除的大錘。如果您想通過清理來發信號終止或取消,則需要使用更微妙的方法。 – Linuxios 2013-03-15 21:23:10

回答

0

這是未經測試的,但線程就像所有東西都可以通過在GC激活之前跳進來進行專門化。所以我認爲你可以添加一個ObjectSpace終結器方法,該方法在Thread被垃圾回收之前執行,以執行你想要的操作。

Ruby: Destructors?