boost · high

Boost.Asio: io_context & the Event Loop

Every Boost.Asio program revolves around an io_context (formerly io_service): it owns the queue of ready completion handlers and the platform machinery that interfaces with the operating system. You schedule work onto it with post() or dispatch() and then call run(), which blocks the calling thread and loops — pulling a ready handler, invoking it, and repeating — returning only when no outstanding work remains; a single thread calling run() yields the classic single-threaded, race-free event loop. Because run() returns immediately when there is nothing pending, long-lived programs such as servers hold an executor_work_guard (via make_work_guard) that counts as outstanding work to keep the loop alive, and they drop the guard to let run() finish or call restart() to reuse a context that has run out of work.

🔑 Key line

io_context is Asio's event loop: it owns the ready-handler queue and OS glue. post()/dispatch() enqueue work; run() blocks the calling thread, pulling and invoking handlers until no work remains. A make_work_guard keeps run() alive when there are no pending ops; restart() reuses it.

The code

boost::asio::io_context io;
// post work, then drive the loop:
boost::asio::post(io, []{ /* a handler */ });
auto guard = boost::asio::make_work_guard(io); // keep run() alive
io.run(); // blocks here, dispatching ready handlers, until no work

What this lesson walks through

  1. 01io_context is the heart of Asio
  2. 02run() drains the handler queue
  3. 03Keep run() alive with a work guard

Every Asio program centers on an io_context (older name: io_service). It owns the queue of ready completion handlers and the machinery that talks to the OS. You schedule work onto it and then call run() to execute that work. One thread calling run() gives you a single-threaded event loop — the classic, race-free Asio model.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Boost.Asio: io_context & the Event Loop and 100+ animated C++ interview lessons.

← Previous
Boost: Peer-Reviewed Libraries & the Incubator for std
Next →
Boost.Asio: The Proactor Model — async ops & completion handlers