Let's say I have two processes: a reader and a writer. How does the writer detect when the reader has finished writing values?
The multiprocessing
module has a queue with a close method that seems custom-built for this purpose. But how do you detect when the queue has been closed?
This doesn't seem to work, as the writer never exits:
import multiprocessing as mp
def getter(q):
while True:
try:
print(q.get())
except Exception:
break
def putter(q):
q.put(1)
q.put(2)
q.close()
q = mp.Queue()
writer = mp.Process(target=putter, args=(q, ))
reader = mp.Process(target=getter, args=(q, ))
reader.start()
writer.start()
writer.join()
reader.join()
Should the reader-writer pair use a sentinel value to signal end of writing? Then what's the point of having the close
method?
EDIT: While this question asks about the Queue module (now queue), I am asking specifically about mp.Queue
and what the correct use of the .close
method is.