- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson05_lock.py
More file actions
Latest commit
25 lines (22 loc) · 727 Bytes
/
Copy pathlesson05_lock.py
File metadata and controls
25 lines (22 loc) · 727 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
# SuperFastPython.com
# example of an asyncio mutual exclusion (mutex) lock
fromrandomimportrandom
importasyncio
# task coroutine with a critical section
asyncdeftask(lock, num, value):
# acquire the lock to protect the critical section
asyncwithlock:
# report a message
print(f'>{num} got the lock, sleep for {value}')
# suspend for a moment
awaitasyncio.sleep(value)
# entry point
asyncdefmain():
# create a shared lock
lock=asyncio.Lock()
# create many concurrent coroutines
coros= [task(lock, i, random()) foriinrange(10)]
# execute and wait for tasks to complete
awaitasyncio.gather(*coros)
# run the asyncio program
asyncio.run(main())