以前對Daemon線程理解有誤差,特記錄說明:php
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。html
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。python
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的解釋存在誤解,特貼出來請你們思考注意:下述描述是錯誤的:函數