Nathan Osman Nathan Osman - 2 months ago 8
Python Question

How to get this thread waiting on a queue to quit?

I've got two threads in my application. One that puts values in a

, and another that pulls them from the
Queue
and processes them.

I am faced with a dilemma when shutting the application down. The thread that processes items in the
Queue
is stuck on:

item = request_queue.get() # this call blocks until an item is available


The only thing that will terminate the thread is if another item is added to the
Queue
- and since the main thread doesn't add anything (because it's shutting down), the application locks.

So... how can I instruct
Queue.get()
to somehow return even if there is nothing on the
Queue
?

Answer

The answer it turns out is quite simple. Pick a value that would be invalid for the code that processes the Queue (None is ideal for that) and push that into the Queue. Then have the Queue processing thread quit when it gets the value:

while True:

    item = request_queue.get()

    if item is None:
        break

    # process the Queue as per normal...