- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson05_event.py
More file actions
Latest commit
34 lines (31 loc) · 906 Bytes
/
Copy pathlesson05_event.py
File metadata and controls
34 lines (31 loc) · 906 Bytes
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 an asyncio event object
fromrandomimportrandom
importasyncio
# task coroutine
asyncdeftask(event, number):
# wait for the event to be set
awaitevent.wait()
# generate a random value between 0 and 1
value=random()
# suspend for a moment
awaitasyncio.sleep(value)
# report a message
print(f'Task {number} got {value}')
# main coroutine
asyncdefmain():
# create a shared event object
event=asyncio.Event()
# create and run the tasks
tasks= [asyncio.create_task(task(event, i))
foriinrange(5)]
# allow the tasks to start
print('Main suspending...')
awaitasyncio.sleep(0)
# start processing in all tasks
print('Main setting the event')
event.set()
# await for all tasks to terminate
_=awaitasyncio.wait(tasks)
# run the asyncio program
asyncio.run(main())