Python 中的守护程序线程对于运行对程序操作不重要的后台任务非常有用。它们允许您在后台运行任务,而无需担心跟踪它们。
Python 提供两种类型的线程:非守护线程 和 守护线程。默认情况下,线程是非守护程序线程。本教程提供了有关 Python 编程中守护程序线程的相关示例的详细说明。
守护程序线程概述
有时,需要在后台执行任务。一种特殊类型的线程用于后台任务,称为守护程序线程。换句话说,守护程序线程在后台执行任务。这些线程处理可能对应用程序有用的非关键任务,但如果它们失败或在操作中被取消,则不会妨碍应用程序。
此外,守护程序线程将无法控制何时终止。一旦所有非守护进程线程都完成,程序将终止,即使在该时间点仍有守护进程线程在运行。
守护线程和非守护线程的区别
守护 进程 | Non-daemon |
---|---|
如果只有守护进程线程在运行(或者没有线程在运行),则进程将退出。 | 如果至少有一个非守护程序线程正在运行,则进程不会退出。 |
守护程序线程用于后台任务。 | 非守护程序线程用于关键任务。 |
守护程序线程突然终止。 | 非守护程序线程运行完成。 |
守护程序线程可以执行以下任务 -
- 创建一个在后台存储 Log 信息的文件。
- 在后台执行 Web 抓取。
- 在后台自动将数据保存到数据库中。
在 Python 中创建守护程序线程
要创建守护程序线程,您需要将 Thread 构造函数的 daemon 属性设置为 True。
t1=threading.Thread(daemon=True)
默认情况下,daemon 属性设置为 None,如果将其更改为 not None,则 daemon 会显式设置线程是否为 daemonic。
例查看以下示例以创建守护进程线程,并使用 daemon 属性检查线程是否为 daemonic。
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)
它将产生以下输出 -
Is Main Thread is Daemon thread: False
如果在主线程中创建线程对象时没有任何参数,则创建的线程将是非守护线程,因为主线程不是守护线程。因此,在主线程中创建的所有线程都默认为非守护进程。但是,我们可以在启动线程之前使用 Thread.daemon 属性将 daemon 属性更改为 True,只能在调用 start() 方法之前使用。
例下面是一个示例 -
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)
在执行上述程序时,我们将得到以下输出 -
Is Main Thread is Daemon thread: False
管理 daemon thread 属性
如果在启动线程后尝试设置线程的守护程序状态,则会引发 RuntimeError。
例这是另一个示例,演示了在启动线程后尝试设置线程的守护进程状态时获取 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)
它将产生以下输出 -
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