(Synchronous) Thread Control

Olivier Parisy olivier.parisy at free.fr
Fri Sep 17 14:40:07 CEST 2004


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,

import threading, time

class IntThread:

     def start(self):
         launched = threading.Event()  # Initially false
         self.listener = self.Listener(launched)

     def stop(self):
         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):
             self.do_stop = False
             self.event = event

         def stop(self):
             self.do_stop = True

         def run(self):
             print "Thread: starting"
             while not self.do_stop:
                 print "Thread: beating"
             print "Thread: exiting"

def test():
     thd = IntThread()
     delay = 5
     print "Main: waiting %s seconds" % delay
     print "Main: done sleeping, stopping thread"
     print "Main: end of program"


More information about the Python-list mailing list