Threaded operation 119 python program - daemon thread

First, the daemon thread

Whether it is a process or thread, follow: Guardian xx xx will wait after the main run is completed destroyed. It is emphasized that: not finished running terminates.

  1. The main process, the operation is completed refers to the main process code has finished running
  2. The main thread, the run is completed refers to the main thread within a process where all non-daemon threads all finished running, the main thread is considered finished running

1.1 Detailed

  1. The main process after the end of its code has finished running the count (daemon was recovered at this point), then the main process will always wait for the child process after recycling non-guardian of the child processes run is completed (or will cause zombie process ), will end.
  2. In other non-main thread after the thread has finished running daemon considered finished running (daemon thread is recovered at this point). Since the end of the end of the process means that the main thread, the whole process will be recycled resources, and the process must be guaranteed to end after non-daemon threads have finished running.

Focus: daemon thread is the guardian of the operating cycle of the process, as long as the program for all non-daemon threads have ended, until the end of daemon threads

Example 1 1.2 daemon thread

from threading import Thread
import time
def sayhi(name):
    time.sleep(2)
    print('%s say hello' %name)

if __name__ == '__main__':
    t=Thread(target=sayhi,args=('nick',))
    t.setDaemon(True) #必须在t.start()之前设置
    t.start()

    print('主线程')
    print(t.is_alive())

The main thread
True

Example 2 1.3 daemon thread

from threading import Thread,enumerate,currentThread
import time

def task():
    print('守护线程开始')
    print(currentThread())
    time.sleep(20)
    print('守护线程结束')
    

def task2():
    print('子线程 start')
    time.sleep(5)
    print(enumerate())
    print('子线程 end')

if __name__ == '__main__':
    t1 = Thread(target=task)
    t2 = Thread(target=task2)
    t1.daemon = True
    t2.start()
    t1.start()
    print('主')

Child thread start
daemon thread starts
main
<the Thread (the Thread-. 1, Started daemon 4360)>
[<_MainThread (MainThread, stopped 15104)>, <the Thread (the Thread-2, Started 15160)>, <the Thread (the Thread-. 1, Started daemon 4360)>]
child thread end

Guess you like

Origin www.cnblogs.com/xichenHome/p/11569096.html