How do you return an item to a queue.Queue? This would be useful in threading or multiprocessing if the task fails, so that the task can not be lost.
The docs for queue.Queue.get() say that the function can "Remove and return an item from the queue," but I believe the use of the word "return" here refers to the function returning the item to the calling thread, not placing it back into the item queue. This is demonstrated by the below sample code just blocks infinitely on the main thread's second queue.Queue.get()
call, instead of making it to the print()
call in the thread.
import time
import threading
import queue
def threaded_func():
thread_task = myqueue.get()
print('thread_task: ' + thread_task)
myqueue = queue.Queue()
myqueue.put('some kind of task')
main_task = myqueue.get()
print('main_task: ' + main_task)
t = threading.Thread(target=threaded_func)
t.daemon = True
t.start()
time.sleep(5)
myqueue.get() # This blocks indefinitely
I have to believe that there is a simple way to put the task back, so what is it? Calling task_done()
and then put()
with the task to put it back into the queue in two operations is not atomic and so could result in a lost item.
One possible, but clunky, solution would be to just try to execute the task again, but then you'd have to add a few extra lines to handle that complexity and I'm not even sure that all failed tasks could necessarily recover in that way.