Interacting with the OS
Boost.Asio can interact with I/O services using synchronous and asynchronous operations. Let’s learn how they behave and what the main differences are.
Synchronous operations
If the program wants to use an I/O service in a synchronous way, usually, it will create an I/O object and use its synchronous operation method:
boost::asio::io_context io_context; boost::asio::steady_timer timer(io_context, 3s); timer.wait();
When calling timer.wait()
, the request is sent to the I/O execution context object (io_context
), which calls the OS to perform the operation. Once the OS finishes with the task, it returns the result to io_context
, which then translates the result, or an error if anything went wrong, back to the I/O object (timer
). Errors are of type boost::system::error_code
. If an error occurs, an exception is thrown.
If we don’t want exceptions to be thrown, we can pass an error object by reference to the synchronous method to capture...