Search code examples
pythonmultithreadingqueueterminate

What is the best way to end this thread when a function is called?


I'm having a bit of trouble with this queue:

import Queue
import threading

class test(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.request_queue = Queue.Queue()

    def addtoqueue(self, item):
        self.request_queue.put(item)

    def run(self):
        while True:
            item = self.request_queue.get(True)
            print item

This simple class implements a threaded queue. Calling test::addtoqueue will append an item to the queue. The thread waits for an item to be added to the queue - and immediately prints it and waits for the next thing.

My problem is application shutdown. What is the best way to terminate the thread? I could use a Condition, but how could I wait for either a notification from the Condition or a new item in the queue?


Solution

  • You can send some poison to the thread to kill it:

    poison = None # something you wouldn't normally put in the Queue
    
    class test(threading.Thread):
    
        def __init__(self):
            threading.Thread.__init__(self)
            self.request_queue = Queue.Queue()
    
        def kill(self):
            self.addtoqueue(poison)
    
        def addtoqueue(self, item):
            self.request_queue.put(item)
    
        def run(self):
            while True:
                item = self.request_queue.get(True)
                if item is poison:
                    # do stuff
                    return # end thread
                print item