Python 3.9+Async programmingfunction
asyncio.to_thread()
threads interop
Runs an ordinary blocking function in a separate thread and lets you await it without stalling the event loop.
Syntax
result = await asyncio.to_thread(func, /, *args, **kwargs)
Good for blocking I/O: requests, file reads, time.sleep. There is no gain for CPU work, because under the GIL the thread takes turns with the loop; use ProcessPoolExecutor via run_in_executor for that. Cancelling the await does not stop the thread: the function runs to the end. Unlike run_in_executor, to_thread propagates contextvars and accepts keyword arguments. Added in 3.9.
Examples
import asyncio
import time
def blocking(name):
time.sleep(0.02) # блокирующий вызов
return name
async def main():
results = await asyncio.gather(
asyncio.to_thread(blocking, 'a'),
asyncio.to_thread(blocking, name='b'),
)
print(results) # → ['a', 'b']
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy