Killing threads

Dave Brueck dbrueck at edgix.com
Mon Mar 19 10:02:47 EST 2001


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Aahz Maruch
> Sent: Friday, March 16, 2001 4:15 PM
> To: python-list at python.org
> Subject: Re: Killing threads
>
>
> In article <mailman.984769881.20374.python-list at python.org>,
> Dave Brueck <dbrueck at edgix.com> wrote:
> >
> >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.
>
> I'm confused.  Is there some reason you're not using Queue.Queue()?

Hi Aahz,

Queue is overkill for simple one-to-one workflows - it's built to be
multi-consumer and multi-producer so every get/put/check requires acquiring
and releasing the Queue's mutex (granted, in most cases that probably won't
make too big of a different, but...).

Anyway, the point here is killing separate threads and my WorkQueue class
was that was the first example that came to mind. Note that whether or not
you use Queue.Queue makes little difference in solving this problem:

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.keepRunning = 0
        self.isRunning = 0
        self.workQ = Queue.Queue(0)

    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.workQ.put_nowait(0) # Wake up thread
        while self.isRunning:
            time.sleep(0.01)

    def AddWork(self, work):
        self.workQ.put_nowait(work) # Wake up the thread

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

                handler(work)
        finally:
            self.isRunning = 0

-Dave





More information about the Python-list mailing list