在Python中加入一个始终运行的线程
请原谅我,如果这是一个愚蠢的问题;我对线程很陌生。 我运行一个线程,将完成当我改变它keeprunning
状态,像这样:在Python中加入一个始终运行的线程
class mem_mon(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.keeprunning = True
self.maxmem = 0
def run(self):
while self.keeprunning:
self.maxmem = max(self.maxmem, ck_mem())
time.sleep(10)
但由于sleep
电话,我经常要等上一段时间他们加入之前。除了创建一个更频繁检查keeprunning
的更快的循环之外,有什么我可以做的更快速地加入线程?例如通过覆盖__del__
或join
?
使用threading.Event作为time.sleep()您可以中断。
class mem_mon(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.keeprunning = True
self.maxmem = 0
self.interrupt = threading.Event()
def run(self):
# this loop will run until you call set() on the interrupt
while not self.interrupt.isSet():
self.maxmem = max(self.maxmem, ck_mem())
# this will either sleep for 10 seconds (for the timeout)
# or it will be interrupted by the interrupt being set
self.interrupt.wait(10)
mem = mem_mon()
mem.run()
# later, set the interrupt to both halt the 10-second sleep and end the loop
mem.interrupt.set()
我能想到的最简单的办法是最丑的,以及 - 我曾经看到怎么杀在Python任何线程,在这个配方:http://icodesnip.com/snippet/python/timeout-for-nearly-any-callable - 我从来没有使用它,因为需要使用锁和队列,但可能性在那里。
当一个互斥事件可以完成相同数量的代码时,丑陋的解决方案并不是必需的 – lunixbochs
你当然是对的,我只是认为值得知道有这样的解决方案。我能想到的一个例子是使用遗留代码的时候 - 杀死一些线程比部分重写它更容易。但正如我所说,我从来没有使用过它,我不知道什么时候或者如果我会。这只是一些好奇,值得了解恕我直言:) – cji
您的链接已损坏。 – preezzzy
使用'threading.Event'或'threading.Condition'对象。 – wberry
谢谢 - 这就是我想说的,不记得有一个单独的课程。 – lunixbochs