Below is code slightly simplified from an example in hte Python docs section 16.6 which shows how to put and get objects from an MP queue.
What if my program puts -- for example -- some big number of objects in the mp queue, and after Y have been gotten out of the result queue, application logic decides that it really doesn't need to process the rest of the objects.
So, how to I delete/purge/flush/clear the contents of the queue? The same question appears to have been asked here, with the answer " but I can't believe that there's no way to do that.
How to clear a multiprocessing queue in python
Thanks
import time, import random
from multiprocessing import Process, Queue, current_process
def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = calculate(func, args)
output.put(result)
def calculate(func, args):
result = func(*args)
return current_process().name, func.__name__, args, result
def plus(a, b):
time.sleep(5*random.random())
return a, b, a + b
def test():
NUMBER_OF_PROCESSES = 4
TASKS2 = [(plus, (i, 8)) for i in range(10000)]
# Create queues
task_queue = Queue()
done_queue = Queue()
# Add more tasks using `put()`
for task in TASKS2:
task_queue.put(task)
print task_queue.qsize()
# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
print 'Unordered results:'
for i in range(len(TASKS1)+len(TASKS2)):
s = done_queue.get()
print s[0], s[3][2]
# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
if __name__ == '__main__':
test()