Python 简明教程

Python - Daemon Threads

Python 中的守护线程对于运行对程序运行非关键的后台任务非常有用。它们允许你在后台运行任务,而不必担心跟踪它们。

Daemon threads in Python are useful for running background tasks that are not critical to the program’s operation. They allow you to run tasks in the background without worrying about keeping track of them.

Python 提供了两种类型的线程:非守护线程和守护线程。默认情况下,线程是非守护线程。本教程提供了有关 Python 编程中守护线程的详细说明和相关示例。

Python provides two types of threads: non-daemon and daemon threads. By default, threads are non-daemon threads. This tutorial provides a detailed explanation with relevant examples about daemon threads in Python programming.

Overview of Daemon Threads

有时,需要在后台执行任务。一种特殊类型的线程用于后台任务,称为守护线程。换句话说,守护线程在后台执行任务。这些线程处理对应用程序有用的非关键任务,但如果不成功或在操作过程中被取消,也不会妨碍应用程序。

Sometimes, it is necessary to execute a task in the background. A special type of thread is used for background tasks, called a daemon thread. In other words, daemon threads execute tasks in the background. These threads handle non-critical tasks that may be useful to the application but do not hamper it if they fail or are canceled mid-operation.

此外,守护线程不能控制何时终止。一旦所有非守护线程完成,程序将终止,即使那时仍有守护线程在运行。

Also, a daemon thread will not have control over when it is terminated. The program will terminate once all non-daemon threads finish, even if there are daemon threads still running at that point of time.

Difference Between Daemon & Non-Daemon Threads

守护线程可以执行以下任务 −

Daemon threads can perform tasks such as −

  1. Create a file that stores Log information in the background.

  2. Perform web scraping in the background.

  3. Save the data automatically into a database in the background.

Creating a Daemon Thread in Python

要创建守护程序线程,你需要将 daemon 属性设置为 Thread 构造函数的 True。

To create a daemon thread, you need to set the daemon property to True of the Thread constructor.

t1=threading.Thread(daemon=True)

默认情况下 daemon 属性设置为 None,如果你将它更改为不是 None,daemon 将明确设置该线程是否为守护程序。

By default the daemon property is set to None, If you change it to not None, daemon explicitly sets whether the thread is daemonic.

Example

查看以下示例以创建守护程序线程并使用 daemon 属性检查线程是否归属于守护程序。

Take a look at the following example to create a daemon thread and check whether the thread daemonic or not using the daemon attribute.

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

It will produce the following output

Daemon thread: True
Is Main Thread is Daemon thread: False

如果在主线程中创建线程对象且没有任何参数,则创建的线程将是非守护程序线程,因为主线程不是守护程序线程。因此,在主线程中创建的所有线程默认情况下都是非守护程序线程。但是,我们可以在 starting the thread 之前使用 Thread.daemon 属性将 daemon 属性更改为 True ,这与调用 start() 方法之前相同。

If a thread object is created in the main thread without any parameters, then the created thread will be a non-daemon thread because the main thread is not a daemon thread. Therefore, all threads created in the main thread default to non-daemon. However, we can change the daemon property to True by using the Thread.daemon attribute before starting the thread, nothing but before calling the start() method.

Example

示例如下:

Here is an 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)

在执行上述程序时,我们将获得以下输出 −

On executing the above program, we will get the following output −

Daemon thread: True
Is Main Thread is Daemon thread: False

Managing the Daemon Thread Attribute

如果你尝试在启动后设置线程的守护程序状态,则将引发 RuntimeError。

If you attempt to set the daemon status of a thread after starting it, then a RuntimeError will be raised.

Example

这里有另一个示例,演示了当你尝试在启动后设置线程的守护程序状态时获得的 RuntimeError。

Here is another example that demonstrates the getting the RuntimeError when you try to set the daemon status of a thread after starting it.

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

It will produce the following 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