如何优雅地退出 python 守护线程
How to exit python deamon thread gracefully
我有如下代码
def run():
While True:
doSomething()
def main():
thread = threading.thread(target = run)
thread.setDaemon(True)
thread.start()
doSomethingElse()
如果我像上面那样写代码,当主线程退出时,Deamon线程也会退出,但可能还在doSomething
.
的进程中
main函数会在外面调用,我不允许在主线程中使用join
,
有什么办法可以让守护线程在主线程完成时优雅地退出。
您不能使用 join
,但您可以设置 Event
并且不使用 daemonic
标志。官方文档如下:
Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
您可以使用线程 threading.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()
我有如下代码
def run():
While True:
doSomething()
def main():
thread = threading.thread(target = run)
thread.setDaemon(True)
thread.start()
doSomethingElse()
如果我像上面那样写代码,当主线程退出时,Deamon线程也会退出,但可能还在doSomething
.
main函数会在外面调用,我不允许在主线程中使用join
,
有什么办法可以让守护线程在主线程完成时优雅地退出。
您不能使用 join
,但您可以设置 Event
并且不使用 daemonic
标志。官方文档如下:
Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
您可以使用线程 threading.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()