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:
开发者_如何学Python 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()
The simplest solution I can think of is the ugliest as well - I once saw how to kill any Thread in Python, in this recipe: http://icodesnip.com/snippet/python/timeout-for-nearly-any-callable - I never used it, using Locks and Queue as needed, but the possibility is there.
精彩评论