ยปCore Development>Code coverage>Doc/includes/mp_workers.py

Python code coverage for Doc/includes/mp_workers.py

#countcontent
1n/aimport time
2n/aimport random
3n/a
4n/afrom multiprocessing import Process, Queue, current_process, freeze_support
5n/a
6n/a#
7n/a# Function run by worker processes
8n/a#
9n/a
10n/adef worker(input, output):
11n/a for func, args in iter(input.get, 'STOP'):
12n/a result = calculate(func, args)
13n/a output.put(result)
14n/a
15n/a#
16n/a# Function used to calculate result
17n/a#
18n/a
19n/adef calculate(func, args):
20n/a result = func(*args)
21n/a return '%s says that %s%s = %s' % \
22n/a (current_process().name, func.__name__, args, result)
23n/a
24n/a#
25n/a# Functions referenced by tasks
26n/a#
27n/a
28n/adef mul(a, b):
29n/a time.sleep(0.5*random.random())
30n/a return a * b
31n/a
32n/adef plus(a, b):
33n/a time.sleep(0.5*random.random())
34n/a return a + b
35n/a
36n/a#
37n/a#
38n/a#
39n/a
40n/adef test():
41n/a NUMBER_OF_PROCESSES = 4
42n/a TASKS1 = [(mul, (i, 7)) for i in range(20)]
43n/a TASKS2 = [(plus, (i, 8)) for i in range(10)]
44n/a
45n/a # Create queues
46n/a task_queue = Queue()
47n/a done_queue = Queue()
48n/a
49n/a # Submit tasks
50n/a for task in TASKS1:
51n/a task_queue.put(task)
52n/a
53n/a # Start worker processes
54n/a for i in range(NUMBER_OF_PROCESSES):
55n/a Process(target=worker, args=(task_queue, done_queue)).start()
56n/a
57n/a # Get and print results
58n/a print('Unordered results:')
59n/a for i in range(len(TASKS1)):
60n/a print('\t', done_queue.get())
61n/a
62n/a # Add more tasks using `put()`
63n/a for task in TASKS2:
64n/a task_queue.put(task)
65n/a
66n/a # Get and print some more results
67n/a for i in range(len(TASKS2)):
68n/a print('\t', done_queue.get())
69n/a
70n/a # Tell child processes to stop
71n/a for i in range(NUMBER_OF_PROCESSES):
72n/a task_queue.put('STOP')
73n/a
74n/a
75n/aif __name__ == '__main__':
76n/a freeze_support()
77n/a test()