2
# Simple example which uses a pool of workers to carry out some tasks.
4
# Notice that the results will probably not come out of the output
5
# queue in the same in the same order as the corresponding tasks were
6
# put on the input queue. If it is important to get the results back
7
# in the original order then consider using `Pool.map()` or
8
# `Pool.imap()` (which will save on the amount of code needed anyway).
14
from multiprocessing import Process, Queue, current_process, freeze_support
17
# Function run by worker processes
20
def worker(input, output):
21
for func, args in iter(input.get, 'STOP'):
22
result = calculate(func, args)
26
# Function used to calculate result
29
def calculate(func, args):
31
return '%s says that %s%s = %s' % \
32
(current_process().name, func.__name__, args, result)
35
# Functions referenced by tasks
39
time.sleep(0.5*random.random())
43
time.sleep(0.5*random.random())
51
NUMBER_OF_PROCESSES = 4
52
TASKS1 = [(mul, (i, 7)) for i in range(20)]
53
TASKS2 = [(plus, (i, 8)) for i in range(10)]
63
# Start worker processes
64
for i in range(NUMBER_OF_PROCESSES):
65
Process(target=worker, args=(task_queue, done_queue)).start()
67
# Get and print results
68
print 'Unordered results:'
69
for i in range(len(TASKS1)):
70
print '\t', done_queue.get()
72
# Add more tasks using `put()`
76
# Get and print some more results
77
for i in range(len(TASKS2)):
78
print '\t', done_queue.get()
80
# Tell child processes to stop
81
for i in range(NUMBER_OF_PROCESSES):
82
task_queue.put('STOP')
85
if __name__ == '__main__':