DEV Community

Nicholus Mush
Nicholus Mush

Posted on

Concurrency in Python

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())
Enter fullscreen mode Exit fullscreen mode

Choose threads for blocking I/O, asyncio for cooperative async tasks, and
processes for CPU-bound workloads.

Top comments (0)