asyncio.to_thread Offloads Blocking Calls

Move blocking work off the event loop with asyncio.to_thread so synchronous checks run in worker threads while other coroutines continue.

PythonResilience

Code

pythonsnippet
29 lines
import asyncio
import threading
import time


def blocking_checksum(limit: int) -> tuple[int, str]:
    # 同步阻塞任务:故意占住一个工作线程
    total = 0
    for value in range(limit):
        total += value * value
    time.sleep(0.01)
    return total, threading.current_thread().name


async def handle(limit: int) -> tuple[int, str]:
    # to_thread:把阻塞函数丢到线程池,事件循环继续调度
    return await asyncio.to_thread(blocking_checksum, limit)


async def main() -> None:
    started = time.perf_counter()
    results = await asyncio.gather(*(handle(n) for n in (10_000, 20_000, 30_000)))
    elapsed = (time.perf_counter() - started) * 1000
    for result, thread_name in results:
        print('checksum:', result, '| ran on:', thread_name)
    print(f'elapsed: {elapsed:.1f}ms')


asyncio.run(main())

How the snippet works

asyncio.to_thread Offloads Blocking Calls keeps everything in the functions blocking_checksum, handle and main.

Iteration happens inside for value in range(limit) — everything outside it runs once. The asynchronous flow is linearized with await, keeping exception handling local.

Points of care

  • Requires asyncio as a package; the snippet will not run without it.

Using it

The entry-point signature is def blocking_checksum(limit: int) -> tuple[int, str]

The demo output is labeled (checksum:, elapsed:); each label names the call that printed it.

blocking_checksum is the public entry point; everything else in the file exists to support it.

Key statements

def blocking_checksum(limit: int) -> tuple[int, str]:
    # 同步阻塞任务:故意占住一个工作线程
    total = 0
    for value in range(limit):
        total += value * value
    time.sleep(0.01)
    return total, threading.current_thread().name
async def handle(limit: int) -> tuple[int, str]:
    # to_thread:把阻塞函数丢到线程池,事件循环继续调度
    return await asyncio.to_thread(blocking_checksum, limit)

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `asyncio` must be present in the project or the import fails at load time.