Python 守护线程在 Windows 上不存在

Man*_*anu 3 python python-multithreading python-3.x

我正在尝试理解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()
Run Code Online (Sandbox Code Playgroud)

观察到的输出:

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


Finishing of thread :Thread-b

Finishing of thread :Thread-a
Run Code Online (Sandbox Code Playgroud)

我预计输出不会包含Finishing of thread :Thread-a因为到那时非守护线程将被杀死,因此守护线程也将被杀死。导致守护线程保持活动状态的代码中的错误是什么?

Tom*_*koo 8

来自文档

\n
\n

线程可以标记为 \xe2\x80\x9cdaemon 线程\xe2\x80\x9d。该标志的意义在于,当只剩下守护线程时,整个 Python 程序就会退出。

\n
\n

线程的问题daemon是,例如,当从 shell(或 IDE)运行时,shell 本身就是主线程!因此,daemon只要 shell 存在,线程就会存在并完成执行。我猜这就是你的情况。

\n

尝试通过 cmd 运行脚本,将会出现您预期的输出。这意味着,线程 a 将不会完成。将代码复制到.py文件后,我通过基本的 python shell (IDLE) 运行它并得到:

\n
>>> Starting of thread :Starting of thread :  Thread-aThread-b\n\nFinishing of thread : Thread-b\nFinishing of thread : Thread-a\n
Run Code Online (Sandbox Code Playgroud)\n

显示 Python IDLE 中上述结果的图像

\n

但是,当运行 时cmd,我得到:

\n
Starting of thread : Thread-a\nStarting of thread : Thread-b\nFinishing of thread : Thread-b\n
Run Code Online (Sandbox Code Playgroud)\n

该图显示了在终端中运行给出的上述结果

\n