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
?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With