Stop a thread on deletion
Sjoerd Op 't Land
sjoerd at intercue.nl
Wed Aug 8 10:43:25 EDT 2007
Hello all,
I'm using threading for generating video content. The trouble is how to
kill the thread, because there are multiple (simultaneous) owners of a
thread. Ideally, a flag would be set when the reference count of the
thread becomes zero, causing the run() loop to quit. Example:
import threading
import time
import gc
class myThread(threading.Thread):
def __init__(self):
self.passedOut = threading.Event()
threading.Thread.__init__(self)
def __del__(self):
self.passedOut.set()
def run(self):
i = 0
while not self.passedOut.isSet():
i += 1
print "Hi %d" % i
time.sleep(0.25)
a = myThread()
a.start()
time.sleep(2.5)
a = None
time.sleep(2.5)
Unfortunately, this doesn't work. When I remove the while-loop, __del__
is called, actually. Appearantly there is still some reference to the
thread while it is running.
I tried gc.get_referrers(self), but it seems to need some parsing. I'm
not sure how to implement that and I'm not sure whether it will work
always or not.
Thanks in advance for any suggestion,
Sjoerd Op 't Land
More information about the Python-list
mailing list