Python 在睡眠时终止线程 [英] Python terminate a thread when it is sleeping

查看:105
本文介绍了Python 在睡眠时终止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从第一个答案中修改了以下代码 链接.

I modified the following code from first answer on this 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 时,我不知道终止它.有人可以帮忙吗?

Once I create an instance of this class and set it to daemon process, I would like to terminate it at a later time, when the thread is sleeping, else wait for it to complete the _target() function and then terminate. I am able to handle the latter case by calling stop method. However, I have no idea of terminating it when the _awake event object is set to False. Can someone please help?

推荐答案

您的线程不必显式sleep.它可以简单地等待另一个线程要求它停止.

Your thread doesn't have to explicitly sleep. It can simply wait for another thread to ask it to stop.

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 事件.(如果另一个线程想要检查它的状态",你可能仍然需要它.我不知道你是否有这个要求).

For this purpose, you don't need the awake event at all. (You might still need it if another thread wants to check its "status". I don't know if that's a requirement you have).

如果没有 awake,你的代码将是:

Without awake, your code will be:

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

这篇关于Python 在睡眠时终止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆