- Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlesson04_barrier.py
More file actions
Latest commit
34 lines (32 loc) · 1.08 KB
/
Copy pathlesson04_barrier.py
File metadata and controls
34 lines (32 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# SuperFastPython.com
# example of using a barrier with processes
fromtimeimportsleep
fromrandomimportrandom
frommultiprocessingimportProcess
frommultiprocessingimportBarrier
# custom function to be executed in a child process
deftask(shared_barrier, ident):
# generate a unique value between 0 and 10
value=random() *10
# block for a moment
sleep(value)
# report result
print(f'Process {ident} got: {value}', flush=True)
# wait for all other processes to complete
shared_barrier.wait()
# protect the entry point
if__name__=='__main__':
# create a barrier for (5 workers + 1 main process)
barrier=Barrier(5+1)
# create the worker processes
workers= [Process(target=task,
args=(barrier, i)) foriinrange(5)]
# start the worker processes
forworkerinworkers:
# start process
worker.start()
# wait for all worker processes to finish
print('Main process waiting on all results...')
barrier.wait()
# report once all processes are done
print('All processes have their result')