0

當python進程的主線程關閉時(通常還是未捕獲的異常),有沒有辦法執行一個函數?如何最終確定主線程?

我希望atexit.register將提供該功能,但顯然它當主線程終止不會被調用 - 只有當已經終止所有線程。因此,作爲打算在代碼不起作用:

import atexit 
import threading 

done = False 

def stop_child_thread(): 
    global done 
    done = True 

def child_thread(): 
    while not done: 
     pass 

atexit.register(stop_child_thread) 
t = threading.Thread(target=child_thread) 
t.start() 

我不想啓動子線程的守護線程,因爲我希望它有機會後自己清理終止前。

我現在唯一能想到的解決方案是定期檢查(從子線程或專用線程)主線程是否仍然存在,如果沒有,請運行我需要的功能。

回答

1

一個想法是將有另一個線程join主線程,然後執行清理:

def cleanup_on_main_thread_exit(): 
    threading.main_thread().join() 
    do_whatever() 

threading.Thread(target=cleanup_on_main_thread_exit).start() 
+0

THX,這個似乎簡單的設置,我在我的問題表現出的工作 - 這是比輪詢更好我打算使用。不幸的是,在實際的代碼中,它導致了一個小小的錯誤:儘管所有線程都成功完成,python解釋器似乎仍然活着;它很容易被CTRL-C停止。我不確定發生了什麼事,我不能用一個小例子來重複它;也許python解釋器退出機制變得困惑。 – max