title: Concurrency in Python — Threads, Asyncio, and Best Practices
published: false
tags: [python, concurrency, asyncio]
Concurrency in Python can be achieved with threads, processes, or asyncio.
This post compares approaches and shows a simple asyncio example.
Example:
import asyncio
async def fetch(n):
await asyncio.sleep(1)
return n
async def main():
res = await asyncio.gather(*(fetch(i) for i in range(3)))
print(res)
asyncio.run(main())
Choose threads for blocking I/O, asyncio for cooperative async tasks, and
processes for CPU-bound workloads.
Top comments (0)