Hi,
I like to use thread to simplify the handling of independant,
blocking tasks. But controling them from a main thread is
not always easy to do in a clean way. So I've written some
generic code whose purpose is to start and stop threads in
a synchronous (blocking) way from the caller's point of view.
Hence, after start() is called you are garanteed that the
thread is running, and after stop() you know it has completed
its tasks.
At the end of this message, you'll find an example of the kind
of code I'm using. Here is its output :
Thread: starting
Main: waiting 5 seconds
Thread: beating
Thread: beating
Thread: beating
Thread: beating
Main: done sleeping, stopping thread
Wrapper: joining thread
Thread: beating
Thread: exiting
It seems like the main thread never exits from join(), in spite of
the timeout and the likeliness of the sub thread ending.
Any idea of what I've done wrong?
Best regards,
Olivier.
import threading, time
class IntThread:
def start(self):
launched = threading.Event() # Initially false
self.listener = self.Listener(launched)
self.listener.start()
launched.wait()
def stop(self):
self.listener.stop()
print "Wrapper: joining thread"
self.listener.join(5) # Should be more than enought
print "Wrapper: after join()"
class Listener(threading.Thread):
def __init__(self, event):
threading.Thread.__init__(self)
self.do_stop = False
self.event = event
def stop(self):
self.do_stop = True
def run(self):
print "Thread: starting"
self.event.set()
while not self.do_stop:
time.sleep(1)
print "Thread: beating"
print "Thread: exiting"
def test():
thd = IntThread()
thd.start()
delay = 5
print "Main: waiting %s seconds" % delay
time.sleep(delay)
print "Main: done sleeping, stopping thread"
thd.stop()
print "Main: end of program"
test()