Boost.Aiso教程 3
2017-05-07 14:13
183 查看
Timer.3-将参数绑定到处理程序
#include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> void print(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* t, int* count) { if (*count < 5) { std::cout << *count << std::endl; ++(*count); t->expires_at(t->expires_at() + boost::posix_time::seconds(1)); t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count)); } } int main() { boost::asio::io_service io; int count = 0; boost::asio::deadline_timer t(io, boost::posix_time::seconds(1)); t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count)); io.run(); std::cout << "Final count is " << count << std::endl; return 0; }
在本教程中我们将修改从教程 Timer.2 程序,使计时器触发一次第二次。这将显示如何将附加参数传递给您的处理程序函数。#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
执行重复的计时器使用澳洲你需要改变你的回调函数,计时器的过期时间,然后开始一个新的异步等待。显然,这意味着回调函数将需要能够访问计时器对象。为此,我们将两个新参数添加到
一个计数器,计时器触发第六次时,我们可以停止该程序。
void print(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* t, int* count) {如上文所述,本教程的程序将使用一个计数器时第六次触发计时器停止运行。然而你会注意到有是没有明确的打电话去问 io_service 停止。记得在教程 Timer.2 中我们得知在io_service::run()函数完成时没有更多的"工作"要做。由不开始一个新的异步等待计时器,当
count达到 5,io_service 将耗尽工作,停止运行。 if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
接下来我们移动的到期时间为沿定时器一秒从以前的到期时间。通过计算相对于旧的新的到期时间,我们可以确保,定时器不会离整个第二次标记在处理任何延误。 t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
然后我们开始一个新的异步等待计时器。正如你所看到的提振:: bind() 函数用来与您的回调处理程序相关联的额外参数。Deadline_timer::async_wait()函数需要一个处理函数 (或函数对象) 与签名
void(const boost::system::error_code&)。将额外的参数绑定将你
boost::asio::placeholders::error, t, count));
}
}
int main()
{
boost::asio::io_service io;
这样我们可以阻止该程序,当计时器触发第六次,将添加一个新的
count变量。 int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
如在步骤 4 中,我们将
main对deadline_timer::async_wait()的调用时。 t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count));
io.run();
最后,只是为了证明,
count变量正在用的
return 0;
}
相关文章推荐
- Boost.Aiso教程 5-同步多线程程序中的处理程序
- Boost.Aiso教程 1
- Boost.Aiso教程 2
- Boost.Aiso教程 4 使用成员函数作为一个句柄
- Boost.Signals 教程
- Boost.Aiso概述 核心概念和功能0
- ultraiso软碟通dmg转iso图文教程
- boost.python入门教程 ----python 嵌入c++
- boost.python 初级教程
- 64位win10下安装xgboost python包的教程
- Poechant快速安装配置教程:Windows + Cygwin + Boost开发环境
- windows下安装xgboost教程
- boost操作xml 5分钟官方教程
- boost.asio包装类st_asio_wrapper开发教程——了解st_asio_wrapper(2016.3.25更新)
- xgboost安装教程,可用
- ArcGIS教程:Iso 聚类非监督分类
- Boost教程网址链接
- 64位win10下安装xgboost python包的教程
- windows7中把ISO文件轻松刻录成光盘的方法(图文教程)
- 摄影教程:ISO值.光圈.快门的关系和运用