Python在休眠时终止一个线程

时间:2016-03-23 08:45:06

标签: multithreading python-2.7

我在这个link的第一个答案中修改了以下代码。

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, target, timeout):
        super(StoppableThread, self).__init__()
        self._target = target
        self._timeout = timeout
        self._stop = threading.Event()
        self.awake = threading.Event()

    def run(self):
        while(not self._stop.isSet()):
            self.awake.clear()
            time.sleep(self._timeout)
            self.awake.set()
            self._target()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

一旦我创建了这个类的实例并将其设置为守护进程,我想稍后在线程休眠时终止它,否则等待它完成_target()函数然后终止。我可以通过调用stop方法来处理后一种情况。但是,当_awake事件对象设置为False时,我无法终止它。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您的主题不必明确sleep。它可以简单地等待另一个线程让它停止。

def run(self):
    while(not self._stop.isSet()):
        self.awake.clear()
        self._stop.wait(self._timeout)  # instead of sleeping
        if self._stop.isSet():
            continue
        self.awake.set()
        self._target()

为此,您根本不需要awake事件。 (如果另一个线程想检查它的“状态”,你可能仍然需要它。我不知道你是否有这个要求。

如果没有awake,您的代码将为:

class StoppableThread(threading.Thread):

    def __init__(self, target, timeout):
        super(StoppableThread, self).__init__()
        self._target = target
        self._timeout = timeout
        self._stop = threading.Event()

    def run(self):
        while not self.stopped():
            self._stop.wait(self._timeout)  # instead of sleeping
            if self.stopped():
                continue
            self._target()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()