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();});
1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

What does it mean the symbol [&] in the initialization of thread??
@user3661321 It's a lambda expression. It's a small function (or function object) defined on the spot. See stackoverflow.com/questions/22327248/c-meaning-of?lq=1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.