Python守护线程在Windows上无法退出

3

我正在尝试理解Python中的守护线程。我的理解是,一旦主线程退出或非守护线程被杀死,守护线程就会被自动终止。然而,在Windows机器上,我的观察结果并非如此。

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()

观察到的输出:

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


Finishing of thread :Thread-b

Finishing of thread :Thread-a

我希望输出结果不包含 Finishing of thread :Thread-a ,因为此时非守护线程已经被杀死,守护线程也应该随之被杀死。是代码中哪里出错导致守护线程仍然存活?

2个回答

8
文档中可以了解到:
线程可以被标记为“守护线程”。这个标志的意义在于,当只剩下守护线程时,整个Python程序将退出。
关于“守护”线程的问题是,在shell(或IDE)中运行时,例如,shell本身就是主线程!因此,“守护”线程将与shell一样长寿,并完成执行。我猜这就是你的情况。
尝试通过cmd运行你的脚本,期望的输出将会出现。也就是说,线程a将不会结束。将你的代码复制到一个.py文件中后,我通过基本的python shell(IDLE)运行它,得到的结果如下:
>>> Starting of thread :Starting of thread :  Thread-aThread-b

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

Python IDLE中的运行结果图像

但是,当通过cmd运行时,我得到了以下信息:

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

Image showing the above result given by running in the terminal


1
我注意到你的输出中有一个>>>。你是在交互式解释器中运行/导入吗?如果是这样,交互式解释器仍将运行,因此daemon线程有足够的时间退出,除非你在两秒内杀死交互式解释器。你需要从常规操作系统shell(例如Windows上的cmd.exe,类UNIX系统上的bash等)中作为独立脚本运行它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接