gpt4 book ai didi

python - 如何在关闭时停止具有无限循环的 Python 守护进程线程?

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:52 27 4
gpt4 key购买 nike

假设我有这样的东西:

import threading
import time

_FINISH = False


def hang():
while True:
if _FINISH:
break
print 'hanging..'
time.sleep(10)


def main():
global _FINISH
t = threading.Thread(target=hang)
t.setDaemon( True )
t.start()
time.sleep(10)

if __name__ == '__main__':
main()

如果我的线程是守护进程,我是否需要全局 _FINISH 来控制中断循环的退出子句?我试过了,但我似乎不需要它 - 当程序退出时(在那种情况下是在 sleep 之后)然后程序终止,这也关闭了线程。

但我也看过该代码 - 这只是不好的做法吗?我可以不用全局标志来控制循环吗?

最佳答案

根据 [Python 3.Docs]: threading - Thread Objects (强调是我的):

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. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

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.

根据上文,从技术上讲,您不需要 _FINISH 逻辑,因为线程将在主线程结束时结束。
但是,根据您的代码,没有人(主线程)发出线程应该结束的信号(类似于_FINISH = True),因此thread 是无用的(因此可以将其删除)。
此外,根据上述建议,您应该在线程之间实现同步机制,并避免将它们设为守护进程(在大多数情况下)。

关于python - 如何在关闭时停止具有无限循环的 Python 守护进程线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com