如何在关机时通过无限循环停止Python守护进程线程?

假设我有这样的东西:import threadingimport time_FINISH = Falsedef hang():while True:if _FINISH:breakprint hanging..time.sleep(10)def main():global _FINISHt = threading.Thread(target=hang)t.setDaemo...

假设我有这样的东西:

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来控制break循环的exit子句?我尝试过,但我似乎并不需要它-当程序退出时(在这种情况下,在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 07001 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 07002.

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

本文标题为:如何在关机时通过无限循环停止Python守护进程线程?

基础教程推荐