Python:线程什么时候终止?显然不是(立即)回来

时间:2017-05-15 15:52:45

标签: python multithreading python-multithreading

我正在使用threading.Thread()执行其工作和return。 它的返回记录在一个打印声明中,所以我很确定 有时候是这样的。但是,依赖threading.active_count()threading.enumerate()线程仍然有效!

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

1 个答案:

答案 0 :(得分:2)

threading模块维护已启动但尚未加入的线程列表。它称之为“活动”列表,但实际上它是一个“尚未加入”的列表。当程序终止时,线程模块将对列表中剩余的内容进行连接。这使您可以执行一个惰性退出程序,程序将一直运行,直到所有工作线程完成。

您可以通过将线程设置为“守护程序”来跳过活动列表。在这种情况下,它不会出现在活动列表中或处于活动计数中。

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()
相关问题