Python: 线程何时终止?显然不(立即)在 return

Python: when does a thread terminate? Oviously not (immediately) at return

我使用的是 threading.Thread()return。 它的 return 记录在打印语句中,所以我确信 有时候是这样的。但是,依靠 threading.active_count()threading.enumerate() 线程仍然处于活动状态!

除了加入MainThread的跟帖之外,还有没有 可以从线程内完成的任何其他事情 安全终止?

threading模块维护一个已经启动但还没有加入的线程列表。它称它为 "active" 列表,但实际上它是一个 "not yet joined" 列表。当程序终止时,线程模块将对列表中剩下的任何内容进行连接。这使您可以延迟退出,程序将停留在 运行 直到其所有工作线程完成。

您可以通过将线程设置为 "daemon" 来跳过活动列表。在这种情况下,它不会出现在活动列表中,也不会出现在活动计数中。

thread = threading.thread(target=somefunction)
thread.daemon = True
thread.start()

如果您创建自己的线程子类,则可以管理 deamon 标志。它甚至可以自行启动,以简化调用者的操作。

class MyWorker(threading.Thread):

    def __init__(self):
        super().__init__()
        self.daemon = True
        self.start()

    def run(self):
        print("do your stuff here")

# example
MyWorker()