boost :: deadline_timer :: async_wait不是异步的 [英] boost::deadline_timer::async_wait is not asynchronous

查看:74
本文介绍了boost :: deadline_timer :: async_wait不是异步的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行一个简单的示例作为测试,我想在5秒钟后执行一个简单的操作.我正在使用带有async_wait的boost :: deadline_timer,但async_wait不会异步等待...这是代码:

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;
}

这是输出:

Second Message
First Message

有一个错误,因为计时器必须在后台等待,这样才能继续执行下一条指令"cout<< FirstMessage \ n";"

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

推荐答案

io.run()仅在其所有作业完成时退出.尝试安排两个具有不同超时时间的 deadline_times ,然后看看会发生什么.(或将io.run()放入另一个线程.)

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

这篇关于boost :: deadline_timer :: async_wait不是异步的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆