user2212461
user2212461

Reputation: 3253

C++: WHILE loop after timed callback blocks the callback?

I am using the from boost suggested solution for a timed callback which can be found here. I am using it to run the timed callback in parallel to other methods. But when I am executing a loop after setting the callback, the callback stops:

//this is the main cpp file

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Hello, world!\n";
}

int main(int argc, char** argv)
{
        boost::asio::io_service io;
        boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
        t.async_wait(print);
        io.run();

        ....some part later I then call a function with while(){} loop inside....
        eng.Loopfunction();

After Loopfunction() is called, the timed callback doesn't work anymore. Do you know how to overcome this problem?

Thanks.

Upvotes: 1

Views: 412

Answers (1)

Ivan
Ivan

Reputation: 2057

the timed callback doesn't work anymore

Is it called only once?

According to the code:

  1. io.run() blocks the main thread
  2. print is called once
  3. io.run() unblocks the main thread
  4. eng.Loopfunction is called

That how it must work. Note that deadline_timer is called only once. If you want timer to be called each second, you need to call deadline_timer::async_wait at the end of print like that:

boost::asio::io_service io;
deadline_timer t(io);

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Hello, world!\n";

  // call this function again in 1 second
  t.expires_from_now( boost::posix_time::seconds(1) );
  t.async_wait(print);
}

int main(int argc, char** argv)
{
    t.expires_from_now( boost::posix_time::seconds(1) );
    t.async_wait(print);
    io.run();

Upvotes: 1

Related Questions