The code below first starts multiple processes. Then it runs a while True loop checking the queue objects. Lastly, it iterates the processes to check if any alive. After all the processes are completed it breaks the while loop.
Unfortunately, it happens while the queue object is not empty. Breaking the loop without getting a data stored in queue could be an easy to oversee data loss. How to modify the code logic so it assures the queue object is empty before breaking the loop?
import time, multiprocessing, os
logger = multiprocessing.log_to_stderr()
def foo(*args):
for i in range(3):
queue = args[0]
queue.put(os.getpid())
items = dict()
for i in range(5):
queue = multiprocessing.Queue()
proc = multiprocessing.Process(target=foo, args=(queue,))
items[proc] = queue
proc.start()
time.sleep(0.1)
while True:
time.sleep(1)
for proc, queue in items.items():
if not queue.empty():
print(queue.get())
if not True in [proc.is_alive() for proc in items]:
if not queue.empty():
logger.warning('...not empty: %s' % queue.get())
break