Nathan Osman Nathan Osman - 11 months ago 42
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
and processes them.

I am faced with a dilemma when shutting the application down. The thread that processes items in the
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
- and since the main thread doesn't add anything (because it's shutting down), the application locks.

So... how can I instruct
to somehow return even if there is nothing on the

Answer Source

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:

    # process the Queue as per normal...