1

我做了一点搜索,发现没有办法在 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()

任何想法 ?无论线程是否完成,我如何在程序终止时杀死 enbableXThread ?

4

2 回答 2

1

程序终止时如何杀死 enbableXThread

如果线程没有任何清理工作要做,则通过将其设置enableXThread.daemonTrue. 这必须在启动线程之前完成:

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

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

您可能还考虑为此使用信号,因为这可能比线程更简单;您可以简单地设置一个小时的警报并让处理程序重置变量。如果您的进程在警报响起之前结束,则不会发生任何事情。请注意,这在 Windows 上不可用。

import signal

X = False

def handle_alarm(signum, frame):
    global X
    X = False

signal.signal(signal.SIGALRM, handle_alarm)

def set_X_true_then_false_later(secs=3600):
    global X
    X = True
    signal.alarm(secs)
于 2013-07-11T15:20:07.633 回答
0

It looks like your problem has already been solved using kindall's suggestions, but if you ever are interested in being able to terminate a thread from another one, the following might be of interest to you.


If you do not mind your code running about ten times slower, you can use the Thread2 class implemented below. An example follows that shows how calling the new stop method should kill the thread on the next bytecode instruction.

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()

The Thread3 class appears to run code approximately 33% faster than the Thread2 class.

于 2014-09-05T14:53:30.397 回答