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).
10 # Copyright (c) 2006-2008, R Oudkerk
11 # All rights reserved.
17 from multiprocessing
import Process
, Queue
, current_process
, freeze_support
20 # Function run by worker processes
23 def worker(input, output
):
24 for func
, args
in iter(input.get
, 'STOP'):
25 result
= calculate(func
, args
)
29 # Function used to calculate result
32 def calculate(func
, args
):
34 return '%s says that %s%s = %s' % \
35 (current_process().name
, func
.__name
__, args
, result
)
38 # Functions referenced by tasks
42 time
.sleep(0.5*random
.random())
46 time
.sleep(0.5*random
.random())
54 NUMBER_OF_PROCESSES
= 4
55 TASKS1
= [(mul
, (i
, 7)) for i
in range(20)]
56 TASKS2
= [(plus
, (i
, 8)) for i
in range(10)]
66 # Start worker processes
67 for i
in range(NUMBER_OF_PROCESSES
):
68 Process(target
=worker
, args
=(task_queue
, done_queue
)).start()
70 # Get and print results
71 print 'Unordered results:'
72 for i
in range(len(TASKS1
)):
73 print '\t', done_queue
.get()
75 # Add more tasks using `put()`
79 # Get and print some more results
80 for i
in range(len(TASKS2
)):
81 print '\t', done_queue
.get()
83 # Tell child processes to stop
84 for i
in range(NUMBER_OF_PROCESSES
):
85 task_queue
.put('STOP')
88 if __name__
== '__main__':