Serbin
Serbin

Reputation: 823

ASIO io_service do not process post handlers on second run() call

I want to be able to post group of handlers to boost::asio::io_service and then run all of them. When all handlers finished, I want to add a new group of them and run() again. And repeat this forever in one thread.

But I have a problem that after the first run() call, next posted jobs are ignored.

Here is a small example (coliru):

#include <iostream>
#include <boost/asio.hpp>

int main()
{
    boost::asio::io_service io;

    io.post([]{ std::cout << "Hello";});
    io.run();
    io.post([]{ std::cout << ", World!" << std::endl; });
    io.run();
}

It will print "Hello" message only and then successfully exit.

Why this example does not print "Hello, World!"?

Boost version: 1.71.0

Upvotes: 2

Views: 248

Answers (1)

rafix07
rafix07

Reputation: 20936

You have to call restart:

A normal exit from the run() function implies that the io_context object is stopped (the stopped() function returns true). Subsequent calls to run(), run_one(), poll() or poll_one() will return immediately unless there is a prior call to restart().

io.post([]{ std::cout << "Hello";});
io.run();
io.post([]{ std::cout << ", World!" << std::endl; });
io.restart(); // just here
io.run();

Upvotes: 3

Related Questions