Python Thread Class: Demon Thread Explained with Example
In Python, a thread is a separate flow of execution that runs concurrently with the main program. You can create a thread using the 'Thread' class from the 'threading' module. This class provides methods and attributes for managing a thread's lifecycle.
A demon thread runs in the background and doesn't prevent the program from exiting. When the main program terminates, all demon threads are automatically terminated without finishing their tasks. To create a demon thread, set the 'daemon' attribute of the 'Thread' class to 'True'.
Here's an example of creating a demon thread in Python:
import threading
import time
def print_numbers():
i = 0
while True:
print(i)
i += 1
time.sleep(1)
t = threading.Thread(target=print_numbers)
t.daemon = True
t.start()
# The main program continues to run
time.sleep(5)
print('Exiting main program')
In this example, we create a function 'print_numbers' that continuously prints numbers. We create a 'Thread' object 't' with this function as its target. We set the 'daemon' attribute of 't' to 'True' and start the thread. The main program sleeps for 5 seconds and then exits. Since 't' is a demon thread, it is terminated automatically when the main program exits. If 't' were not a demon thread, it would keep running even after the main program exits.
原文地址: https://www.cveoy.top/t/topic/lPuN 著作权归作者所有。请勿转载和采集!