File size: 697 Bytes
82c9012 |
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 |
from random import random
import asyncio
# task coroutine
async def task(semaphore, number):
# acquire the semaphore
async with semaphore:
# generate a random value between 0 and 1
value = random() + 2
# block for a moment
await asyncio.sleep(value)
# report a message
print(f"Task {number} got {value}")
# main coroutine
async def main():
# create the shared semaphore
semaphore = asyncio.Semaphore(2)
# create and schedule tasks
tasks = [asyncio.create_task(task(semaphore, i)) for i in range(10)]
# wait for all tasks to complete
_ = await asyncio.wait(tasks)
# start the asyncio program
asyncio.run(main())
|