Python 3.5+Async programmingfunction
asyncio.run_coroutine_threadsafe()
threads interop
Submits a coroutine to an event loop running in another thread and returns a concurrent.futures.Future to wait for the result.
Syntax
future = asyncio.run_coroutine_threadsafe(coro, loop)
This is the bridge from a plain thread into the loop: a worker thread may not call create_task, but this function is thread-safe. It returns a concurrent.futures Future, waited on with fut.result(timeout), which blocks. Calling result() on the loop's own thread hangs the program: the loop waits for itself. The loop is passed explicitly, because a foreign thread has no current loop.
Examples
import asyncio
async def add(a, b):
await asyncio.sleep(0.01)
return a + b
def worker(loop):
fut = asyncio.run_coroutine_threadsafe(add(2, 3), loop)
return fut.result(timeout=1) # блокирует рабочий поток, а не цикл
async def main():
loop = asyncio.get_running_loop()
print(await asyncio.to_thread(worker, loop)) # → 5
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy