您的位置:首页 > 大数据 > 人工智能

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>
执行重复的计时器使用澳洲你需要改变你的回调函数,计时器的过期时间,然后开始一个新的异步等待。显然,这意味着回调函数将需要能够访问计时器对象。为此,我们将两个新参数添加到
print
功能︰指向一个计时器对象的指针。
一个计数器,计时器触发第六次时,我们可以停止该程序。
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&)
。将额外的参数绑定将你
print
的功能转换成正确的签名相匹配的函数对象。有关如何使用 boost::bind(),请参阅Boost.Bind 文档以了解更多信息。在此示例中,刺激:: bind () 的 boost::asio::placeholders::error 参数是传递给处理程序的错误对象的命名的占位符。当启动异步操作,并且如果使用 boost::bind(),您必须指定只与处理程序的参数列表匹配的参数。Timer.4 教程中,您将看到,可以省略此占位符,是否该参数不需要通过回调处理程序。 t->async_wait(boost::bind(print,
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 中,我们将
print
功能所需要的额外参数绑定从
main
deadline_timer::async_wait()的调用时。 t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count));

io.run();
最后,只是为了证明,
count
变量正在用的
print
处理程序函数,我们将打印出其新的值。 std::cout << "Final count is " << count << std::endl;

return 0;
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  boost aiso C++