Python守护程序线程

时间:2020-02-23 14:42:35  来源:igfitidea点击:

在本教程中,我们将学习Python Daemon Thread。
在上一教程中,我们了解了Python getattr()函数。

Python守护程序线程

要开始本教程,您应该具有有关线程的基本知识。
基本上有两种类型的线程。
一种是守护线程。
另一个是非守护线程。

当非守护进程线程阻塞主程序时,如果它们没有死,则退出它们。
守护程序线程在运行时不会阻止主程序退出。
当主程序退出时,关联的守护程序线程也会被杀死。

Python守护程序线程示例

我们有一个简单的程序,其中创建两个线程。
其中之一将花费更长的时间执行,因为我们增加了2秒的睡眠时间。
让我们运行以下程序并观察输出。

import threading
import time

def print_work_a():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(2)
  print('Finishing of thread :', threading.currentThread().name)

def print_work_b():
  print('Starting of thread :', threading.currentThread().name)
  print('Finishing of thread :', threading.currentThread().name)

a = threading.Thread(target=print_work_a, name='Thread-a')
b = threading.Thread(target=print_work_b, name='Thread-b')

a.start()
b.start()

您将获得如下输出。

Starting of thread : Thread-a
Starting of thread : Thread-b
Finishing of thread : Thread-b
Finishing of thread : Thread-a

因此,已执行的线程和随后的主线程都退出并终止程序。

现在,我们将Thread a作为守护线程。
然后,您将看到输出的差异。
因此,让我们按照以下步骤编辑之前的代码。

import threading
import time

def print_work_a():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(2)
  print('Finishing of thread :', threading.currentThread().name)

def print_work_b():
  print('Starting of thread :', threading.currentThread().name)
  print('Finishing of thread :', threading.currentThread().name)

a = threading.Thread(target=print_work_a, name='Thread-a', daemon=True)
b = threading.Thread(target=print_work_b, name='Thread-b')

a.start()
b.start()

在创建线程a时,请注意另外的参数" daemon = True"。
这就是我们将线程指定为守护程序线程的方式。
下图显示了程序现在的输出。

请注意,即使守护程序线程正在运行,程序也会退出。

什么时候守护程序线程有用

在大型项目中,一些线程在那里执行一些后台任务,例如发送数据,执行定期垃圾回收等。
它可以由非守护进程线程完成。
但是,如果使用了非守护程序线程,则主线程必须手动跟踪它们。
但是,使用守护程序线程,主线程可以完全忘记此任务,并且该任务将在主线程退出时完成或者终止。

请注意,您仅应将守护程序线程用于不重要的任务(如果任务没有完成或者介于两者之间)。