3

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();});
user3661321
  • 103
  • 1
  • 10
  • With respect to the "Thanks, I solved in this way" addition: [How does accepting an answer work](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – sehe Jan 30 '15 at 20:59

2 Answers2

3

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.)

sehe
  • 374,641
  • 47
  • 450
  • 633
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
2

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
Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • What does it mean the symbol [&] in the initialization of thread?? – user3661321 Jan 30 '15 at 18:55
  • @user3661321 It's a lambda expression. It's a small function (or function object) defined on the spot. See http://stackoverflow.com/questions/22327248/c-meaning-of?lq=1 – sehe Jan 30 '15 at 19:19