Asynchronous Programming with async and await
asyncio runs many I/O tasks concurrently in one thread using coroutines.
Intermediate
import asyncio
async def poll(sensor, delay):
await asyncio.sleep(delay) # yields control while waiting
return f"{sensor} ok"
async def main():
results = await asyncio.gather(poll("temp", 1), poll("light", 1))
print(results) # both finish after ~1 s, not 2 s
asyncio.run(main())
Ideal for network servers, scrapers and IoT gateways with many slow connections. Never call blocking functions inside async code.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.