Python

asyncio.to_thread — Run Blocking Code

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap a blocking function so it doesn't freeze the event loop. asyncio.to_thread (3.9+) schedules the call onto the default executor and awaits the result.
Python
Raw
import asyncio
import time
import hashlib

def cpu_heavy(n: int) -> str:
    """Blocking — would freeze the event loop if called directly."""
    h = hashlib.sha256(b"seed").digest()
    for _ in range(n):
        h = hashlib.sha256(h).digest()
    return h.hex()

async def main():
    # Three CPU-heavy calls in parallel without blocking the loop
    results = await asyncio.gather(
        asyncio.to_thread(cpu_heavy, 100_000),
        asyncio.to_thread(cpu_heavy, 100_000),
        asyncio.to_thread(cpu_heavy, 100_000),
    )
    print([r[:8] for r in results])

asyncio.run(main())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.