Concurrency & performance
asyncio, threading, multiprocessing, and profiling-friendly performance patterns.
How to Run Coroutines Concurrently with asyncio.gather in Python
Run multiple async coroutines concurrently and collect their results in the order they were passed.
import asyncio
async def fetch_data(name: str, delay: float) -> str:
"""Simulate an async operation (e.g., API call) with a delay."""
await asyncio.sleep(delay)
return f"{name} data (after {delay}s)"
async def main() -> None:
"""Run multiple coroutines concurrently with asyncio.gather."""
resul…
How to Use asyncio Lock to Protect a Shared Counter in Python
This code demonstrates how to use an asyncio.Lock to safely increment a shared counter from multiple concurrent coroutines.
import asyncio
async def increment(counter, lock, increments):
for _ in range(increments):
async with lock:
counter[0] += 1
async def main():
counter = [0]
lock = asyncio.Lock()
tasks = [
increment(counter, lock, 1000)
for _ in range(5)
]
await asyncio.gath…
Limit Concurrency with asyncio.Semaphore in Python
Use asyncio.Semaphore to cap how many async tasks run at once, throttling a batch of coroutines to a set concurrency limit.
import asyncio
import random
async def fetch_data(i: int, semaphore: asyncio.Semaphore) -> str:
async with semaphore:
print(f"Task {i} starts")
await asyncio.sleep(random.uniform(0.1, 0.5))
print(f"Task {i} finishes")
return f"Result {i}"
async def main() -> None:
semaphore …
asyncio Condition wait notify pattern in Python
Coordinate coroutines with asyncio.Condition: workers wait for notifications and the main task notifies one or all of them.
import asyncio
async def worker(condition, name):
async with condition:
print(f"{name} waiting...")
await condition.wait()
print(f"{name} notified!")
async def main():
condition = asyncio.Condition()
tasks = [asyncio.create_task(worker(condition, f"worker-{i}")) for i in range(3…
Browse by section
Each section groups closely related Python snippets.
Concurrency & performance — Python code examples
What you will find here
This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.