永发信息网

boost:asio 在哪个线程回调

答案:1  悬赏:80  手机版
解决时间 2021-02-14 14:15
  • 提问者网友:棒棒糖
  • 2021-02-14 10:34
boost:asio 在哪个线程回调
最佳答案
  • 五星知识达人网友:往事埋风中
  • 2021-02-14 10:43
这里我们将每秒回调一次,来演示如何回调函数参数的含义
  #include
  #include
  #include
  #include
  首先,调整一下timer的持续时间,开始一个异步等待.显示,回调函数需要访问timer来实现周期运行,所以我们再介绍两个新参数
  指向timer的指针
  一个int*来指向计数器
  void print(const asio::error& ,
  asio::deadline_timer* t, int* count)
  {
  我们打算让这个函数运行6个周期,然而你会发现这里没有显式的方法来终止io_service.不过,回顾上一节,你会发现当 asio::io_service::run()会在所有任务完成时终止.这样我们当计算器的值达到5时(0为第一次运行的值),不再开启一个新的异步等待就可以了.
  if (*count < 5)
  {
  std::cout << *count << " ";
  ++(*count);
  ...
  然后,我们推迟的timer的终止时间.通过在原先的终止时间上增加延时,我们可以确保timer不会在处理回调函数所需时间内的到期.
  (原文:By calculating the new expiry time relative to the old, we can ensure that the timer does not drift away from the whole-second mark due to any delays in processing the handler.)
  t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
  然后我们开始一个新的同步等待.如您所见,我们用把print和他的多个参数用boost::bind函数合成一个的形为void(const asio::error&)回调函数(准确的说是function object).
  在这个例子中, boost::bind的asio::placeholders::error参数是为了给回调函数传入一个error对象.当进行一个异步操作,开始 boost::bind时,你需要使用它来匹配回调函数的参数表.下一节中你会学到回调函数不需要error参数时可以省略它.
  t->async_wait(boost::bind(print,
  asio::placeholders::error, t, count));
  }
  }
  int main()
  {
  asio::io_service io;
  int count = 0;
  asio::deadline_timer t(io, boost::posix_time::seconds(1));
  和上面一样,我们再一次使用了绑定asio::deadline_timer::async_wait()
  t.async_wait(boost::bind(print,
  asio::placeholders::error, &t, &count));
  io.run();
  在结尾,我们打印出的最后一次没有设置timer的调用的count的值
  std::cout << "Final count is " << count << " ";
  return 0;
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯