Async (asyncio) await in Python
asyncio lets your program do multiple tasks at the same time without waiting.
import asyncio
async def hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(hello())
Multiple tasks:
gather accept multiple functions-> run all at same time, -> wait for finish all ->return results if any
ie Order 2 dishes and wait at table ???????
import asyncio
async def task1():
await asyncio.sleep(2)
print("Task 1 done")
async def task2():
await asyncio.sleep(1)
print("Task 2 done")
async def main():
await asyncio.gather(task1(), task2())
asyncio.run(main())
output:
Task 2 done
Task 1 done
Creating Tasks: runs in background
Starts task in background immediately
ie Order food, then go do shopping ????, come back later
async def work():
await asyncio.sleep(2)
print("Work done")
async def main():
task = asyncio.create_task(work())
print("Doing other things...")
await task
asyncio.run(main())
|
code:
|
output:
|
Fetch multiple urls:
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://example.com",
"https://google.com"
]
tasks = [fetch(url) for url in urls]
results = await asyncio.gather(*tasks)
print("Fetched", len(results), "pages")
asyncio.run(main())
Semaphore: ???? Only N tasks run at once
sem = asyncio.Semaphore(2)
async def work(i):
async with sem:
print(f"Task {i} running")
await asyncio.sleep(2)
async def main():
await asyncio.gather(*(work(i) for i in range(5)))
asyncio.run(main())
Queue:
import asyncio
queue = asyncio.Queue()
async def producer():
for i in range(5):
await queue.put(i)
print("Produced", i)
async def consumer():
while True:
item = await queue.get()
print("Consumed", item)
queue.task_done()
async def main():
asyncio.create_task(consumer())
await producer()
await queue.join()
asyncio.run(main())