之前對Daemon線程理解有偏差,特記錄說明:
一、什么是Daemon
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.
線程可以被標識為"Daemon線程",Daemon線程表明整個Python主程序只有在Daemon子線程運行時可以退出。該屬性值繼承自父線程,可通過setDaemon()函數設定該值。
Note
Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
注意
Daemon線程會被粗魯的直接結束,它所使用的資源(已打開文件、數據庫事務等)無法被合理的釋放。因此如果需要線程被優雅的結束,請設置為非Daemon線程,並使用合理的信號方法,如事件Event。
daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are left.
isDaemon()
setDaemon()
Python主程序當且僅當不存在非Daemon線程存活時退出。
即:主程序等待所有非Daemon線程結束后才退出,且退出時會自動結束(很粗魯的結束)所有Daemon線程。
亦理解為:Daemon設置為子線程是否隨主線程一起結束,默認為False。如果要隨主線程一起結束需要設置為True。
二、Daemon線程用途:
Daemons are only useful when the main program is running, and it's okay to kill them off once the other non-daemon threads have exited. Without daemon threads, we have to keep track of them, and tell them to exit, before our program can completely quit. By setting them as daemon threads, we can let them run and forget about them, and when our program quits, any daemon threads are killed automatically.
Daemon線程當且僅當主線程運行時有效,當其他非Daemon線程結束時可自動殺死所有Daemon線程。如果沒有Daemon線程的定義,則必須手動的跟蹤這些線程,在程序結束前手動結束這些線程。通過設置線程為Daemon線程,則可以放任它們運行,並遺忘它們,當主程序結束時這些Daemon線程將自動被殺死。
三、對線程的Daemon的誤解
看到部分文章里對線程中Daemon的解釋存在誤解,特貼出來請大家思考注意:下述描述是錯誤的:
- 設置線程為守護線程,主線程退出后,子線程仍運行直到任務結束。