Python 简明教程
Python - Daemon Threads
Python 中的守护线程对于运行对程序运行非关键的后台任务非常有用。它们允许你在后台运行任务,而不必担心跟踪它们。
Python 提供了两种类型的线程:非守护线程和守护线程。默认情况下,线程是非守护线程。本教程提供了有关 Python 编程中守护线程的详细说明和相关示例。
Overview of Daemon Threads
有时,需要在后台执行任务。一种特殊类型的线程用于后台任务,称为守护线程。换句话说,守护线程在后台执行任务。这些线程处理对应用程序有用的非关键任务,但如果不成功或在操作过程中被取消,也不会妨碍应用程序。
此外,守护线程不能控制何时终止。一旦所有非守护线程完成,程序将终止,即使那时仍有守护线程在运行。
Creating a Daemon Thread in Python
要创建守护程序线程,你需要将 daemon 属性设置为 Thread 构造函数的 True。
t1=threading.Thread(daemon=True)
默认情况下 daemon 属性设置为 None,如果你将它更改为不是 None,daemon 将明确设置该线程是否为守护程序。
Example
查看以下示例以创建守护程序线程并使用 daemon 属性检查线程是否归属于守护程序。
import threading
from time import sleep
# function to be executed in a new thread
def run():
# get the current thread
thread = threading.current_thread()
# is it a daemon thread?
print(f'Daemon thread: {thread.daemon}')
# Create a new thread and set it as daemon
thread = threading.Thread(target=run, daemon=True)
# start the thread
thread.start()
print('Is Main Thread is Daemon thread:', threading.current_thread().daemon)
# Block for a short time to allow the daemon thread to run
sleep(0.5)
它将生成以下 output −
Daemon thread: True
Is Main Thread is Daemon thread: False
如果在主线程中创建线程对象且没有任何参数,则创建的线程将是非守护程序线程,因为主线程不是守护程序线程。因此,在主线程中创建的所有线程默认情况下都是非守护程序线程。但是,我们可以在 starting the thread 之前使用 Thread.daemon 属性将 daemon 属性更改为 True ,这与调用 start() 方法之前相同。
Example
示例如下:
import threading
from time import sleep
# function to be executed in a new thread
def run():
# get the current thread
thread = threading.current_thread()
# is it a daemon thread?
print(f'Daemon thread: {thread.daemon}')
# Create a new thread
thread = threading.Thread(target=run)
# Using the daemon property set the thread as daemon before starting the thread
thread.daemon = True
# start the thread
thread.start()
print('Is Main Thread is Daemon thread:', threading.current_thread().daemon)
# Block for a short time to allow the daemon thread to run
sleep(0.5)
在执行上述程序时,我们将获得以下输出 −
Daemon thread: True
Is Main Thread is Daemon thread: False
Managing the Daemon Thread Attribute
如果你尝试在启动后设置线程的守护程序状态,则将引发 RuntimeError。
Example
这里有另一个示例,演示了当你尝试在启动后设置线程的守护程序状态时获得的 RuntimeError。
from time import sleep
from threading import current_thread
from threading import Thread
# function to be executed in a new thread
def run():
# get the current thread
thread = current_thread()
# is it a daemon thread?
print(f'Daemon thread: {thread.daemon}')
thread.daemon = True
# create a new thread
thread = Thread(target=run)
# start the new thread
thread.start()
# block for a 0.5 sec for daemon thread to run
sleep(0.5)
它将生成以下 output −
Daemon thread: False
Exception in thread Thread-1 (run):
Traceback (most recent call last):
. . . .
. . . .
thread.daemon = True
File "/usr/lib/python3.10/threading.py", line 1203, in daemon
raise RuntimeError("cannot set daemon status of active thread")
RuntimeError: cannot set daemon status of active thread