Daemon: Setting a thread is a daemon thread, which means that this is not a very important thread, for such a thread, as long as the main thread runs the end, it will exit directly. If a thread is not a daemon thread, it will not exit until the thread runs the end, but wait for all non-daemon threads to run and exit. Simple concept: The daemon thread is hung and the child threads are hung up. Non-daemon threads, the main thread hangs, and the child threads continue to continue.
1. Daemon Thread & non-daemon thread
Example:
A. Daemon process:
Import Threading,timedef _demon (): For I in range (1,5): print (i) time.sleep (2) t = Threading. Thread (Target=_demon) T.setdaemon (True) #把线程设置为守护进程, to be placed in front of start execution T.start () print ("End the Process") output: 1end the process
B, non-daemon process:
Import Threading,timedef _demon (): For I in range (1,5): print (i) time.sleep (2) t = Threading. Thread (Target=_demon) T.setdaemon (False) T.start () print ("End the Process") output: 1end the process234
Note: The default is the non-daemon process, to set the process as the primary process, it is necessary to manually open.
If you set a thread as the daemon thread, it means that you are saying that this thread is unimportant and that the process exits without waiting for the thread to exit.
if your main thread exits without waiting for those child threads to complete, set the Daemon property of those threads. That is, before the thread starts (Thread.Start ()), call the Setdeamon () function to set the daemon flag for the threads. (Thread.setdaemon (True)) indicates that the thread is "unimportant". If you want to wait for a sub-thread to finish and then exit, you don't have to do anything. , or Thread.setdaemon (false) is called, setting the value of daemon to false. The new child thread inherits the parent thread's daemon flag. The entire python will not end until all non-daemon threads have exited, that is, there is no non-daemon thread in the process.
7, Seventh week-network programming-daemon process