先杀死python中的线程

2024-09-29 19:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一点搜索,发现在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?在


Tags: 函数内存self程序falsetruedef时间
2条回答

how I can kill enbableXThread when the program terminates

如果线程没有任何清理任务,请将enableXThread.daemon设置为True,使其成为守护程序线程。在启动线程之前必须执行以下操作:

self.enableXThread = Thread(target=self.enableX) 
self.enableXThread.daemon = True
self.enableXThread.start()

否则,使用exit标志(线程检查是否应该退出的全局变量)或Event处理程序。在

您也可以考虑为此使用一个信号,因为这可能比线程更简单;您只需设置一个小时的警报,然后让处理程序重置变量。如果你的过程在警报响之前结束,什么都不会发生。请注意,这在Windows上不可用。在

^{pr2}$

看起来你的问题已经用kindall的建议解决了,但是如果你有兴趣从另一个线程中终止一个线程,你可能会感兴趣。在


如果您不介意代码运行速度慢十倍,可以使用下面实现的Thread2类。下面的一个例子展示了如何调用新的stop方法来杀死下一个字节码指令上的线程。在

import threading
import sys

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace


class Thread3(threading.Thread):

    def _bootstrap(self, stop_thread=False):
        def stop():
            nonlocal stop_thread
            stop_thread = True
        self.stop = stop

        def tracer(*_):
            if stop_thread:
                raise StopThread()
            return tracer
        sys.settrace(tracer)
        super()._bootstrap()

################################################################################

import time

def main():
    test = Thread2(target=printer)
    test.start()
    time.sleep(1)
    test.stop()
    test.join()

def printer():
    while True:
        print(time.time() % 1)
        time.sleep(0.1)

if __name__ == '__main__':
    main()

Thread3类似乎比Thread2类快大约33%。在

相关问题 更多 >

    热门问题