On this page
asyncio.run_coroutine_threadsafe
Prev: asyncio.run | Up: asyncio | Next: asyncio.set_event_loop
Rel: asyncio.AbstractEventLoop, asyncio.AbstractServer, asyncio.all_tasks, asyncio.as_completed
Ref: docs.python.org — asyncio.run_coroutine_threadsafe
Tags: #public #python3 #stdlib #asyncio
Import
import asyncio
from asyncio import run_coroutine_threadsafe
Signature & Overview
asyncio.run_coroutine_threadsafe(coro, loop)
Submit a coroutine object to a given event loop.
Usage
import asyncio
import threading
loop = asyncio.new_event_loop()
t = threading.Thread(target=loop.run_forever, daemon=True)
t.start()
try:
fut = asyncio.run_coroutine_threadsafe(asyncio.sleep(0, result="cross-thread"), loop)
assert fut.result(timeout=2) == "cross-thread"
finally:
loop.call_soon_threadsafe(loop.stop)
t.join()
loop.close()
Gotchas
- Returns a
concurrent.futures.Future, NOT anasyncio.Future: Call.result(timeout=...)from the non-async thread to wait for the outcome.
REPL Inspect
from asyncio import run_coroutine_threadsafe
help(run_coroutine_threadsafe)
Linked from
Related notes
- tuts/python3/stdlib_module/asyncio/run Linked here; links to this page; shared tags: #asyncio, #stdlib
- tuts/python3/stdlib_module/asyncio/set_event_loop 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