user3661321
user3661321

Reputation: 103

boost::deadline_timer::async_wait is not asynchronous

I execute a simple example as a test, I want execute a simple operation after 5 seconds. I am using the boost::deadline_timer with async_wait, but async_wait not wait asynchronously... This is the code:

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Second Message\n";
}

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

  boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
  t.async_wait(print);
  io.run();
  std::cout << "First Message\n";
  return 0;
}

And this is output:

Second Message
First Message

There is an error because, the timer would have to wait in background and so to continue the execution of next instruction that is "cout<<"FirstMessage\n";"

The expected behavior is print "First Message" and after print "Second Message"


Thanks, I solved in this way:

    boost::asio::io_service io;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
    t.async_wait(print);
    std::thread thread([&]{io.run();});

Upvotes: 3

Views: 1704

Answers (2)

sehe
sehe

Reputation: 392833

What Michael said. Just yesterday I was writing this sample in chat:

Live On Coliru

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

int main() {
    boost::asio::io_service svc;
    boost::asio::deadline_timer timer(svc, boost::posix_time::seconds(2));
    timer.async_wait([](boost::system::error_code ec) { std::cout << ec.message() << '\n'; });

    std::thread th([&] { svc.run(); });

    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "first\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "bye\n";
    
    th.join();
}

Output:

first
Success
bye

Upvotes: 2

Michael Anderson
Michael Anderson

Reputation: 73450

io.run() exits only when all its jobs are complete. Try scheduling two deadline_times with different timeouts and see what happens. (Or put the io.run() into another thread.)

Upvotes: 3

Related Questions