Stopping a thread from another one

Peter Hansen peter at engcorp.com
Wed Jun 23 03:41:15 CEST 2004


Fabiano Sidler wrote:

> I would prefer, if I end the subthreads by the main thread.
> Is there any chance?

The usual idiom is something like this:

class StoppableThread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         self._running = False


     def stop(self):
         self._running = False


     def run(self):
         while self._running:
             # do stuff here that loops periodically to allow
             # the flag to be checked


Then from the main thread you can keep track of the child
threads and do xxx.stop() on each of them, then an optional
threading.Thread.join() call (check the docs for that).

This can be made more sophisticated as required.

-Peter



More information about the Python-list mailing list