from multiprocessing import Process, Queue
def worker_main(q):
while True:
message = q.get()
q = Queue()
worker = Process(target=worker_main, args=(q,))
worker.start()
q.close()
worker.join()
I expect the call to q.get in worker_main() to throw an exception and exit after q is closed. Instead it hangs ever after the queue is closed in the main process.
My use case seems to be slightly different than the common examples which show Queue.put in the worker process and Queue.get in the main process.
In a main process I'm producing tasks that need to be distributed to a pool of worker processes via a queue. However when the tasks are complete I close the queue to indicate to the worker processes it's time to exit.
Perhaps I do not understand the documentation, but I think it's clear that future calls to get should raise an exception after close.
get([block[, timeout]])Remove and return an item from the queue. If optional args
blockisTrue(the default) andtimeoutisNone(the default), block if necessary until an item is available. Iftimeoutis a positive number, it blocks at most timeout seconds and raises thequeue.Emptyexception if no item was available within that time. Otherwise (block isFalse), return an item if one is immediately available, else raise thequeue.Emptyexception (timeout is ignored in that case).Changed in version 3.8: If the queue is closed,
ValueErroris raised instead ofOSError.
q.get()can be called before the queue is closed. That sounds like a bug, but maybe you can workaround by using timeouts ? - Vincent Fourmondcloseindicates the current process will not put any more items in the queue.worker_mainis executed in a different process than the one that calledq.close(). - chepnerNoneis nice) per known reader of the queue. If some processes had terminated there will be too many None's in the queue... but it hasn't been a problem for me. - tdelaneycloseis also documented as "usually unnecessary for most code". Its job isn't to pass messages to other processes, but to help the current process manage process-local resources. - chepnerQueue.closecloses the current process' queue handle. It doesn't close the queue in other processes. - MisterMiyagi