[python-win32] Restart/re-run a thread

geoff imageguy1206 at gmail.com
Thu Oct 27 15:47:21 CEST 2011


The python docs are pretty clear that there is no way to external stop a
thread and this was a design decision.

Typically, I have used a threading.Event to control the actions of the
worker threads from a loop in the main program.

Setup each worker thread as a loop using the event.wait() method to block
the loop.   When you are ready for all of the threads to proceed, use the
controller thread and event.set().  All of the worker threads will exit the
blocking state of their loop and proceed with execution.  Once finished,
they return to the  event.wait() mode.

To stop the threads, I typically use another thread.Event object called
"keepgoing" and test for that at the top of the worker threads processing
loop.  When the threads have finished processing and you want them to stop,
you can set the keepgoing event to false.


The example below is from memory, so be careful;

keepgoing = threading.Event()
keepgoing.set()   # evaluates to True

startprocess = threading.Event()
startprocess.clear()  # evaluates to False

class worker(threading.Thread):
    def __init__(self, keepgoing, startprocess):
         while keepgoing:
              if startprocess:
                       ... do someprocessing here
              else:
                   startprocess.wait()            #blocks the thread waiting
for the event to be set.


Note that if you need to pass objects into the worker thread, I would
suggest placing in a collections.deque.  One the startprocess is set, you
can use deque.pop() to take the object out of the deque in a thread safe
way.

Hope this helps.

BTW, I am not sure if this is for education purposes or for production, but
debugging threads is REALLY HARD, so make sure this is something you really
need to do.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-win32/attachments/20111027/bf16091d/attachment.html>


More information about the python-win32 mailing list