- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson05_semaphore.py
More file actions
Latest commit
28 lines (25 loc) · 762 Bytes
/
Copy pathlesson05_semaphore.py
File metadata and controls
28 lines (25 loc) · 762 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
# SuperFastPython.com
# example of using an asyncio semaphore
fromrandomimportrandom
importasyncio
# task coroutine
asyncdeftask(semaphore, number):
# acquire the semaphore
asyncwithsemaphore:
# 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 the shared semaphore
semaphore=asyncio.Semaphore(2)
# create and schedule tasks
tasks= [asyncio.create_task(task(semaphore, i))
foriinrange(10)]
# wait for all tasks to complete
_=awaitasyncio.wait(tasks)
# start the asyncio program
asyncio.run(main())