示例工程 18-asyncio-event-loop

18-asyncio-event-loop/03-to-thread-offload/to_thread_offload.py

python · 0.6 KB

"""演示用 asyncio.to_thread 卸载阻塞调用。"""
 
from __future__ import annotations
 
import asyncio
import time
 
 
def blocking_io(delay: float = 0.05) -> str:
    time.sleep(delay)
    return "done"
 
 
async def offload(delay: float = 0.05) -> str:
    return await asyncio.to_thread(blocking_io, delay)
 
 
async def main() -> None:
    started = time.perf_counter()
    results = await asyncio.gather(offload(), offload(), offload())
    elapsed = time.perf_counter() - started
    print(f"offloaded: {results} {elapsed:.2f}s")
    print(f"threads_concurrent: {elapsed < 0.12}")
 
 
if __name__ == "__main__":
    asyncio.run(main())