我做了一点搜索,发现在python中没有办法杀死一个线程,但是像我这样的问题怎么解决呢?在
我有一个函数,它在一个小时内将X设置为True,然后再将其设置回False。在
有时程序完成的时间少于所需的小时,但线程仍在运行并在内存中造成垃圾。在
def enableX():
self.x=True
sleep(3600)
self.x=False
def function1():
self.enableXThread=Thread(target=self.enableX)
self.enableXThread.start()
有什么想法吗?当程序终止时,不管线程是否完成,如何杀死enablexthread?在
如果线程没有任何清理任务,请将
enableXThread.daemon
设置为True
,使其成为守护程序线程。在启动线程之前必须执行以下操作:否则,使用exit标志(线程检查是否应该退出的全局变量)或
Event
处理程序。在您也可以考虑为此使用一个信号,因为这可能比线程更简单;您只需设置一个小时的警报,然后让处理程序重置变量。如果你的过程在警报响之前结束,什么都不会发生。请注意,这在Windows上不可用。在
^{pr2}$看起来你的问题已经用kindall的建议解决了,但是如果你有兴趣从另一个线程中终止一个线程,你可能会感兴趣。在
如果您不介意代码运行速度慢十倍,可以使用下面实现的
Thread2
类。下面的一个例子展示了如何调用新的stop
方法来杀死下一个字节码指令上的线程。在Thread3
类似乎比Thread2
类快大约33%。在相关问题 更多 >
编程相关推荐