Event loop
The event loop is the asyncio scheduler: it runs ready callbacks and coroutines, waits for I/O, fires timers, and resumes tasks when their futures complete.
Detailed Explanation
Asyncio is not "the OS runs my coroutines". One loop, usually on the main thread, owns the process. It keeps a queue of ready handles, a heap of timed callbacks, and a selector (or proactor on Windows) of file descriptors. Each turn it runs ready work, then blocks in the selector until something happens or a timer expires.
await is a yield back to that loop. The current task is parked. The loop runs other tasks. When the awaited future completes, the task is marked ready again. If a task computes for 200ms without awaiting, the loop does not turn, sockets do not get read, and timeouts do not fire. That is a blocked loop, and it looks like the whole service froze.
asyncio.run creates a loop, runs one main coroutine, and shuts the loop down. Nested asyncio.run is illegal. In libraries, get_running_loop() is the safe lookup; get_event_loop() on 3.10+ without a running loop is a warning path you should not use.
One loop per thread is the model. You can start a loop in another thread with asyncio.new_event_loop and run_forever, then submit work with asyncio.run_coroutine_threadsafe. Cross-thread calls into a running loop must go through that API or you will corrupt the loop.
Policies (asyncio.WindowsSelectorEventLoopPolicy, uvloop) replace the loop implementation. They do not change the rule: do not block, do not share a loop across threads without the threadsafe APIs, do not create tasks on a loop that is not running.
Debugging a stuck service starts with "is the loop turning?". A stuck CPU coroutine, a synchronous lock, or a huge json.loads on the loop thread are the usual answers.
Code Examples
import asyncio
async def ticks() -> None:
loop = asyncio.get_running_loop()
print(loop.is_running()) # True
print(loop.time()) # monotonic clock used for timeouts
# asyncio.run(ticks())# Blocking the loop: do not do this in production.
async def frozen() -> None:
import time
time.sleep(1) # no await; other tasks cannot run# From another thread, schedule work on the running loop.
# asyncio.run_coroutine_threadsafe(coro, loop).result(timeout=2)Common Gotchas
CPU work or `time.sleep` on the loop thread
every connection waits. Offload with `to_thread` or a process pool.
`asyncio.run` inside a running loop
`RuntimeError`. Use `await` or `create_task`.
Using a loop object from the wrong thread
only `run_coroutine_threadsafe` and thread-safe queue APIs.
`loop.time()` is monotonic
do not mix it with `time.time()` for deadlines.