繁体   English   中英

在python中加入始终运行的线程

[英]joining an always-running thread in python

如果这是一个愚蠢的问题,请原谅我。 我对线程很陌生。 我正在运行的线程将在更改其keeprunning状态时完成,如下所示:

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-我从未使用过它,而是根据需要使用Locks和Queue,但是可能性是存在的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM