Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Queue, 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?

like image 241
Nathan Osman Avatar asked May 13 '11 04:05

Nathan Osman


1 Answers

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...
like image 185
Nathan Osman Avatar answered Nov 19 '22 07:11

Nathan Osman