- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson04_barrier.py
More file actions
Latest commit
34 lines (32 loc) · 1.02 KB
/
Copy pathlesson04_barrier.py
File metadata and controls
34 lines (32 loc) · 1.02 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 threads
fromtimeimportsleep
fromrandomimportrandom
fromthreadingimportThread
fromthreadingimportBarrier
# custom function to be executed in a new thread
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'Thread {ident} got: {value}')
# wait for all other threads to complete
shared_barrier.wait()
# protect the entry point
if__name__=='__main__':
# create a barrier for (5 threads + 1 main thread)
barrier=Barrier(5+1)
# create the new threads
threads= [Thread(target=task,
args=(barrier, i)) foriinrange(5)]
# start the new threads
forthreadinthreads:
# start thread
thread.start()
# wait for all new threads to finish
print('Main thread waiting on all results...')
barrier.wait()
# report once all thread are done
print('All threads have their result')