python主线程休眠,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()

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?

解决方案

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值