On this page
asyncio.to_thread
Prev: asyncio.timeout_at | Up: asyncio
Rel: asyncio.AbstractEventLoop, asyncio.AbstractServer, asyncio.all_tasks, asyncio.as_completed
Ref: docs.python.org — asyncio.to_thread
Tags: #public #python3 #stdlib #asyncio
Import
import asyncio
from asyncio import to_thread
Signature & Overview
asyncio.to_thread(func, /, *args, **kwargs)
Asynchronously run function func in a separate thread.
Usage
import asyncio
def blocking_sum(n: int) -> int:
return sum(range(n))
async def main():
total = await asyncio.to_thread(blocking_sum, 100)
assert total == 4950
asyncio.run(main())
Gotchas
- Best way to run blocking I/O inside
async def: Offloads the callable to the default thread pool while propagatingcontextvarsautomatically. - Not cancellable mid-flight: Cancelling the awaiting task does not forcibly kill the underlying OS thread.
REPL Inspect
from asyncio import to_thread
help(to_thread)
Linked from
Related notes
- tuts/python3/stdlib_module/asyncio/timeout_at Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractEventLoop Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/AbstractServer Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/all_tasks Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/as_completed Linked here; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/Barrier shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseEventLoop shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseProtocol shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/BaseTransport shared tags: #asyncio, #stdlib