/*
标题:演示boost::asio::deadline_timer如何使用
作者:Kagula
知识点:[1]boost::asio::strand实例让多根线程逐个执行
[2]boost::asio::io_service的run会等待boost::asio::strand实例
中的线程全部执行完毕。
测试环境:Visual Studio 2013 Update2
最后更新日期:2014-06-04
*/
#include "stdafx.h"
#include <stdio.h>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class printer
{
public:
printer(boost::asio::io_service& io)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(0)
{
//boost::asio::strand::wrap()确保print1和pirnt2线程不会同时运行
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
~printer()
{
printf("Final count is %d\n", count_);
}
//两个回调函数共享 count_ 变量
void print1()
{
if (count_ < 10)
{
printf("Timer 1: %d \n", count_++);
timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
}
}
void print2()
{
if (count_ < 10)
{
printf("Timer 2: %d \n", count_++);
timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
}
private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};
int _tmain(int argc, _TCHAR* argv[])
{
//等待deadline_timer实例运行完毕
boost::asio::io_service io;
printer p(io);
io.run();
return 0;
}
演示boost::asio::deadline_timer如何使用
最新推荐文章于 2023-04-05 00:46:23 发布