run_in_thread¶
Start each call in a new thread and get a concurrent.futures.Future back. This lets you run blocking code without waiting for it.
from python_wrap import run_in_thread
@run_in_thread
def add(a: int, b: int) -> int:
return a + b
future = add(1, 2)
assert future.result() == 3 # waits; re-raises the function's exception, if any
When to use it¶
- You want to fire off blocking work and collect the result later.
- You want a
Futureyou can pass around, wait on with a timeout, or attach callbacks to. - To await blocking code from
asynccode,asyncio.to_threadis usually a better fit:run_in_threadreturns a plainFuture, not an awaitable.
Behaviour¶
future.result()is the equivalent of v0.1'sthread.join(), plus the return value.async deffunctions run withasyncio.runin the new thread (their own event loop), and the wrapper itself is a plain function returning aFuture.- The caller's
contextvarsare copied into the thread. - Options:
daemon=True(do not keep the interpreter alive) andname=(thread name).
import asyncio
from python_wrap import run_in_thread
@run_in_thread(daemon=True, name="worker")
async def fetch() -> str:
await asyncio.sleep(0.01)
return "done"
assert fetch().result() == "done"