boost · advanced
Boost.Asio: Strands — Lock-Free Handler Serialization
When io_context.run() executes on multiple threads, two completion handlers for the same connection can run simultaneously on different threads and race on that connection's buffers and state; wrapping everything in a mutex works but is error-prone and adds contention on the hot path. A strand solves this elegantly: it is an executor that guarantees the handlers bound to it never run concurrently and execute in the order they were submitted, providing serialization without any explicit lock — you opt in by wrapping a handler with bind_executor(strand, handler) or by constructing the socket on a strand executor via make_strand. The canonical concurrency model in Asio is therefore one strand per connection, binding all of a connection's handlers to its strand so that connection's state is touched by at most one thread at a time while different connections continue to run in parallel across the thread pool — yielding both safety and scalability without scattering locks through the code.
With multiple run() threads, handlers for one connection can race. A strand is an executor that guarantees its handlers never run concurrently and run in submission order — serialization WITHOUT a mutex (bind_executor / make_strand). The idiom: one strand per connection → that connection's state is safe while different connections run in parallel.
The code
auto strand = boost::asio::make_strand(io);// bind handlers to the strand so they never run concurrently:boost::asio::async_read(sock, buf, boost::asio::bind_executor(strand, [](auto ec, auto n) { /* safe: serialized */ }));What this lesson walks through
- 01The problem: concurrent handlers race
- 02A strand serializes — without locks
- 03Idiom: one strand per connection
Run io_context.run() on several threads and two completion handlers for the SAME connection can fire on different threads at once — racing on that connection's buffers and state. You could wrap everything in a mutex, but that's error-prone and adds contention on the hot path.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Boost.Asio: Strands — Lock-Free Handler Serialization and 100+ animated C++ interview lessons.