这几天看《Boost程序库完全开发指南》的第十二章有介绍Asio的使用方法,介绍很简单,只介绍了定时器、网络通信。下面对书中提到的定时器编程代码(
boost_async_timer_bind.cpp
)如下:
/*
author:AlexChen
date:2014/04/22
#g++ -g -o main boost_async_timer_bind.cpp -lboost_system
*/
#define BOOST_REGEX_NO_LIB
#define BOOST_DATE_TIME_SOURCE
#define BOOST_SYSTEM_NO_LIB
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace std;
using namespace boost;
using namespace boost::asio;
void SyncTimer()
{
io_service ios;
deadline_timer t(ios,posix_time::seconds(2));
cout<<t.expires_at()<<" "<<time(NULL)<<endl;
t.wait();
cout<<"Hello!SyncTimer...."<<" "<<time(NULL)<<endl;
}
void Print(const boost::system::error_code&)
{
cout<<"Hello!AsyncTimer...."<<" "<<time(NULL)<<endl;
}
void AsyncTimer()
{
io_service ios;
deadline_timer t(ios,posix_time::seconds(2));
cout<<t.expires_at()<<" "<<time(NULL)<<endl;
t.async_wait(Print);
cout<<"It show before t expired..."<<" "<<time(NULL)<<endl;
ios.run();
}
class a_timer
{
private:
int count;
int count_max;
function<void()> f;
deadline_timer t;
public:
template<typename F>
a_timer(io_service& ios,int x,F func):
f(func),count_max(x),count(0),
t(ios,posix_time::millisec(500))
{
t.async_wait(boost::bind(&a_timer::call_func,
this,placeholders::error));
}
void call_func(const boost::system::error_code& e)
{
if(count >= count_max){
return;
}
++count;
f();
t.expires_at(t.expires_at() + posix_time::millisec(500));
t.async_wait(boost::bind(&a_timer::call_func,this,placeholders::error));
}
};
void Print1()
{
cout<<"Hello,Print1..."<<endl;
}
void Print2()
{
cout<<"Hello,Print2..."<<endl;
}
void TestBind()
{
io_service ios;
a_timer at1(ios,5,Print1);
a_timer at2(ios,5,Print2);
ios.run();
}
int main()
{
cout<<endl<<"Test SyncTimer ...."<<endl;
SyncTimer();
cout<<endl<<"Test AsyncTimer ...."<<endl;
AsyncTimer();
cout<<endl<<"Test TestBind ...."<<endl;
TestBind();
cout<<endl<<"successful!..."<<endl;
}