Chapter 15, concurrent programming Guardian thread

Chapter 15, concurrent programming Guardian 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('主')

Daemon thread: Non-threaded code has finished running daemon, daemon threads will be over (the guardian of non-daemon threads)

         The main thread after thread has finished running other non-daemon considered the end (daemon thread will be recovered at this time

Emphasize : the main thread is a non-threaded daemon (process that contains the thread)

Summary: The reason for introducing daemon is the end of the main thread means the end of the process, the whole process will be recycled resources, and the process must be guaranteed to end after non-daemon threads have finished running

The difference between daemons and daemon threads

  • Daemon: the main process code has finished running, the daemon will be over
  • Daemon threads: non-daemon thread has finished running, the guardian of the thread end

Guess you like

Origin www.cnblogs.com/demiao/p/11536608.html