如何优雅地退出python守护程序线程 [英] How to exit python deamon thread gracefully

查看:0
本文介绍了如何优雅地退出python守护程序线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码

def run():
  While True:
    doSomething()
def main():
  thread = threading.thread(target = run)
  thread.setDaemon(True)
  thread.start() 
  doSomethingElse()

如果我像上面那样编写代码,当主线程退出时,守护线程将退出,但可能仍在doSomething的进程中。

Main函数将在外部调用,我不允许在主线程中使用join, 有什么方法可以使守护程序线程在主线程完成后正常退出。

推荐答案

您可以使用THREADthreading.Event通知子线程何时退出主线程。

示例:

class DemonThead(threading.Thread):

    def __init__(self):
        self.shutdown_flag = threading.Event()

    def run(self):
        while not self.shutdown_flag:
            # Run your code here
            pass

def main_thread():
    demon_thread = DemonThead()
    demon_thread.setDaemon(True) 
    demon_thread.start()
    
    # Stop your thread
    demon_thread.shutdown_flag.set()
    demon_thread.join()

这篇关于如何优雅地退出python守护程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆