Killing threads

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


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]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)
q.Start()
...
q.AddWork(work)
q.AddWork(work)
...
q.Stop()

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:
            threading.Thread(target=self.__thread).start()

    def Stop(self):
        'Shutdown'
        self.keepRunning = 0
        self.sem.release() # Wake up the thread
        while self.isRunning:
            time.sleep(0.01)

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

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

                work = workQ.pop(0)
                handler(work)
        finally:
            self.isRunning = 0





More information about the Python-list mailing list