线程集守护进程不工作

Threading Set Daemon not working

一个非常简单的脚本。

test.py

import temp
temp.start()

temp.py

import threading, time
f=open("output.txt","w")
def temp():
    for i in range(5):
        f.write(str(i))
        time.sleep(5)
    f.close()
def start():
    t=threading.Thread(target=temp)
    t.setDaemon(True)
    t.start()

我希望守护线程在主进程 test.py 退出时完成 immediately.But daemon 线程与主进程一起退出并且不像 daemon 那样运行。我是这里缺少一些基本的东西?

这在

的 python 文档中有详细描述

https://docs.python.org/3/library/threading.html

最相关的位是:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly.

术语 'daemon' 的重载和否定的扭曲可能会使这有点混乱,但它归结为:python 程序仅 退出 在它的所有线程完成后,除了守护线程,如果没有其他非守护线程被留下,它们将被简单地终止。在你的例子中,这意味着程序在它有机会做任何事情之前退出杀死你的守护线程(或者,相反,如果你 setDaemon(false),直到你的线程完成才退出)。

补充 , a possible solution for your question is to use join(),在你的情况下:

t.join()

更多关于加入“what is the use of join() in python threading

可以在以下位置找到以实用方式解释的很好的指南:https://realpython.com/intro-to-python-threading/