Post your own functors into io_context

126

We've learned that asynchronous tasks completion handlers are invoked from io_context::run. However we've been talking about some I/O asynchronous operations so far. But sometimes you need just to execute a given functor within io_context::run polling loop. To do that you should use boost::asio::post function:

namespace io = boost::asio;
using tcp = io::ip::tcp;
using error_code = boost::system::error_code;

io::io_context io_context;
auto work_guard = io::make_work_guard(io_context); // A facility that makes life easier
// Schedule some tasks or not
io_context.run();

// ...
// Somewhere else, another thread may be:
io::post(io_context, [&]
{
    std::cout << "Hey, I'm inside io_context::run polling loop!\n";
});

boost::asio::post posts a given functor into the execution queue and that functor is executed along with other functors and completion handlers in a general way. The function is thread-safe so feel free to post from different threads.

For example, you could use it to cancel an asynchronous operation on a socket by closing it in a safe way:

io::io_context io_context;
tcp::socket socket(io_context);
// ...
io::async_read(socket, buffer, [&] (error_code error, std::size_t bytes_transferred)
{
    if(!error)
    {
        // Do your duty
    }
    else
    {
        // The socket has been closed or something else has happened
        // We don't really care what exactly, just drop the session
    }
});
io_context.run();

// ...
// Somewhere else, another thread may be:
io::post(io_context, [&]
{
    error_code error;
    socket.close(error);
});
Share this page:

Learning plan

A bigger example of a server where you'll need to apply everything you've learned so far
Principles you should take into consideration during the development of your applications
How to keep io_context::run running even when there is no work to do
11. Post your own functors into io_context
How execute a regular code within io_context::run polling loop
We've dealt with a single-threaded environment so far; now it's time to go multithreading
A special execution model with a custom load balancer
14. Timers
Working with asynchronous timers within io_context polling loop