I am new to Boost::asio
and I am currently looking at io_context
.
In the docs https://www.boost.org/doc/libs/1_75_0/doc/html/boost_asio/reference/io_context.html shown is the following example:
{
...
}
...
boost::asio::io_context io_context;
// Submit a function to the io_context.
boost::asio::post(io_context, my_task);
// Submit a lambda object to the io_context.
boost::asio::post(io_context,
[]()
{
...
});
// Run the io_context until it runs out of work.
io_context.run();
However, I would like to be able to post
even after io_context.run()
has been called.
Essentially, something like this:
#include <boost/asio.hpp>
int value = -1;
void my_task()
{
value = 42;
}
int main() {
boost::asio::io_context io_context;
// Submit a function to the io_context.
//boost::asio::post(io_context, my_task);
// Run the io_context until it runs out of work.
io_context.run();
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work(io_context.get_executor());
// Submit a lambda object to the io_context.
boost::asio::post(io_context,
[]()
{
my_task();
});
assert(value == 42);
}
After compiling the above with g++ -o a example.cpp -lboost_system -lpthread
I am getting an assertion failure. What is the "right" way to accomplish this?