简体   繁体   中英

joining an always-running thread in python

Forgive me if this is a dumb question; I am very new to threading. I am running a thread that will finish when I change it's keeprunning status like so:

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)

But due to the sleep call, I often have to wait a while before they join. Other than creating a faster loop that checks keeprunning more often, is there anything I can do to join the thread more instantaneously? For example by overriding __del__ or join ?

Use threading.Event as an time.sleep() you can interrupt.

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,但是可能性是存在的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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