Runtime systems · intermediate

Async execution and the event loop

Asynchronous execution lets a task suspend while awaiting an external completion; an event loop selects ready tasks or callbacks and runs them according to the runtime's queueing rules.

Why it matters

Async code can keep a small number of threads responsive during many I/O waits, but blocking callbacks and mistaken ordering assumptions can stall all tasks sharing the loop.

Mental model

How to reason about async execution and the event loop

Await records where the task should resume and returns control. When the awaited operation completes, its continuation becomes ready; the loop runs ready work one piece at a time unless the runtime dispatches it elsewhere.

Analogy

A receptionist starts a request, leaves a callback number, and serves other visitors while waiting; when the result arrives, the request rejoins the ready line.

Examples

See the boundary, not just the happy path

Worked example · Suspend for network I/O

response = await fetch(url)

The current async task yields while the request is pending, allowing the event loop to run other ready work.

Worked example · Preserve responsiveness

split CPU work or move it to a worker

Long computation does not become nonblocking merely because its function is async; it must yield or run outside the loop thread.

Useful contrast · Not necessarily parallel

two callbacks alternate on one event-loop thread

Their lifetimes overlap, but only one callback executes at a time, so the behavior is concurrent rather than parallel.

Common mistakes

Misconceptions to remove early

Blocking inside a callback

Synchronous sleep, file access, or CPU-heavy work can prevent the loop from servicing every other ready task on that thread.

Assuming one universal queue order

Microtasks, timers, I/O completions, and platform-specific queues have defined but different priorities. Consult the runtime rather than infer order from source layout.

Quick check

Can you predict the result?

1. What does await normally do while an operation is incomplete?
  • It suspends the async task's continuation and returns control so other ready work can run
  • It always creates a new operating-system process
  • It makes the awaited operation complete immediately
Answer: It suspends the async task's continuation and returns control so other ready work can run
2. Why can a CPU-heavy async callback freeze an event-loop application?
Answer: Async syntax does not preempt the computation; the loop thread cannot run other callbacks until that work yields or finishes.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster