Reference library

Concurrency & performance

asyncio, threading, multiprocessing, and profiling-friendly performance patterns.

3 matches
Concurrency & performance medium

How to Pause and Resume Threads with threading.Event in Python

Use threading.Event to pause and resume worker threads in Python, controlling execution flow with set and clear methods.

threading events concurrency
Python
import threading
import time

workers = []

def worker(name, event):
    for i in range(10):
        event.wait()
        print(f"{name} step {i}")
        time.sleep(0.1)

def pause_worker(name):
    global pause_event
    for w in workers:
        if w.name == name:
            pause_event.clear()
            print(…
10 0 Open
Concurrency & performance easy

How to set a timeout with asyncio.wait_for in Python

Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.

asyncio timeout concurrency
Python
import asyncio

async def slow_task():
    await asyncio.sleep(3)
    return "finished"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

if __name__ == "__main__":
    asyncio.run(main())
13 0 Open
Concurrency & performance medium

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.

asyncio concurrency semaphore
Python
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 …
13 0 Open

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.