Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
CPU-bound vs I/O-bound scaling:
In Simple Words:
- I/O-Bound: Use AsyncIO or Threading (waiting for DB, network sockets).
- CPU-Bound: Use
ProcessPoolExecutoror background task queues (Celery/RabbitMQ) across multiple CPU cores.
python
from concurrent.futures import ProcessPoolExecutor
import math
def calculate_primes(n):
return [x for x in range(2, n) if all(x % d != 0 for d in range(2, int(math.isqrt(x)) + 1))]
# Runs across all machine CPU cores in parallel:
with ProcessPoolExecutor() as pool:
prime_chunks = list(pool.map(calculate_primes, [100000, 200000, 300000]))