Threading with Boost.Asio
I/O execution context objects are thread-safe; their methods can be called from different threads safely. That means that we can use a separate thread to run the blocking io_context.run()
method and leave the main thread unblocked to carry on with other unrelated tasks.
Let’s now explain the different ways to configure the asynchronous application in terms of how to use threads.
Single-threaded approach
The starting point and preferred solution for any Boost.Asio application should follow a single-threaded approach where the I/O execution context object runs in the same thread where the completion handlers are being processed. These handlers must be short and non-blocking. Here is an example of a steady timer completion handler running in the same thread as the I/O context, the main thread:
#include <boost/asio.hpp> #include <chrono> #include <iostream> using namespace std::chrono_literals; void handle_timer_expiry( ...