Python asyncio Advanced
Advanced loop management, low-level scheduling, and platform-aware asyncio usage.
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Event Loop Management
import asyncio
import threading
async def main():
loop = asyncio.get_running_loop()
event = asyncio.Event()
def notify():
loop.call_soon_threadsafe(event.set)
threading.Thread(target=notify).start()
await event.wait()
print("notified")
asyncio.run(main())# Use `call_soon_threadsafe()` when another thread must notify the loop.
import asyncio
import threading
async def echo():
return "ok"
async def main():
loop = asyncio.get_running_loop()
result_holder = {}
def worker():
future = asyncio.run_coroutine_threadsafe(echo(), loop)
result_holder["value"] = future.result()
t = threading.Thread(target=worker)
t.start()
await asyncio.sleep(0.1)
t.join()
print(result_holder["value"])
asyncio.run(main())# Use `run_coroutine_threadsafe()` with a loop reference.
## Migration and Platform Notes
More in Python asyncio
Python asyncio Recipes
Real-world asyncio recipes for HTTP concurrency, retries, and pipelines.
Python asyncio Streams and Subprocesses
Network streams, subprocesses, and non-blocking integration patterns.
Python asyncio Cheat Sheet
Core asyncio patterns for writing concurrent I/O-bound Python programs with async and await.