[Python]Threading.Thread之Daemon线程
之前对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的解释存在误解,特贴出来请大家思考注意:下述描述是错误的:
- 设置线程为守护线程,主线程退出后,子线程仍运行直到任务结束。