- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson04_event.py
More file actions
Latest commit
37 lines (35 loc) · 1.02 KB
/
Copy pathlesson04_event.py
File metadata and controls
37 lines (35 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
35
36
37
# SuperFastPython.com
# example of using an event object with threads
fromtimeimportsleep
fromrandomimportrandom
fromthreadingimportThread
fromthreadingimportEvent
# custom function to be executed in a new thread
deftask(shared_event, number):
# wait for the event to be set
print(f'Thread {number} waiting...')
shared_event.wait()
# begin work, generate a random number
value=random()
# block for a fraction of a second
sleep(value)
# report a message
print(f'Thread {number} got {value}')
# protect the entry point
if__name__=='__main__':
# create a shared event object
event=Event()
# create a suite of threads
threads= [Thread(target=task,
args=(event, i)) foriinrange(5)]
# start all threads
forthreadinthreads:
thread.start()
# block thread a moment
print('Main thread blocking...')
sleep(2)
# trigger all threads
event.set()
# wait for all threads to terminate
forthreadinthreads:
thread.join()