Killing threads

Dave Brueck dbrueck at
Fri Mar 16 20:09:22 CET 2001

> -----Original Message-----
> From: python-list-admin at
> [mailto:python-list-admin at]On Behalf Of Steve Purcell
> > I have th program below. How does one go about kill a thread once
> > started? Why is there no method for killing threads? I thought del
> > would do it but obviously it doesn't.
> You should think about using a synchronisation mechanism
> (threading.Condition, threading.Semaphore, Queue.Queue) so that the worker
> thread can exit itself when told to do so by the main thread changing the
> synchronising object.

Or just a simple flag. Here's a class I use in designs that use work flows
(work objects pulled off one queue, processed, and moved onto the next
queue). If you just need an always-processing background thread you can
eliminate all the stuff with the semaphore.

Use it like this:

q = WorkQueue(someHandlerFunc)

class WorkQueue:
    'Waits (on a background thread) for work to appear on a queue and then
dispatches it to a handler'

    def __init__(self, handler):
        self.handler = handler
        self.sem = threading.Semaphore(0)
        self.keepRunning = 0
        self.isRunning = 0
        self.workQ = []

    def Start(self):
        'Start processing'
        self.keepRunning = 1
        if not self.isRunning:

    def Stop(self):
        self.keepRunning = 0
        self.sem.release() # Wake up the thread
        while self.isRunning:

    def AddWork(self, work):
        self.sem.release() # Wake up the thread

    def __thread(self):
        self.isRunning = 1
        sem = self.sem
        workQ = self.workQ
        handler = self.handler
            while 1:
                sem.acquire() # Wait for work to appear
                if not self.keepRunning:
                    break # Someone called Stop so quit

                work = workQ.pop(0)
            self.isRunning = 0

More information about the Python-list mailing list