1、同步:
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using std::cout; using std::endl; int main() { boost::asio::io_service io; boost::asio::deadline_timer t(io,boost::posix_time::seconds(5)); t.wait(); cout<<"Hello,world!"<<endl; return 0; }
//过5秒输出 "Hello,world!"
2、异步:相当于现在银行取票排队,时间到了会通知你。
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using std::cout; using std::endl; void print(const boost::system::error_code& error) { cout<<"Hello,world!"<<endl; } int main() { boost::asio::io_service io; boost::asio::deadline_timer t(io,boost::posix_time::seconds(5)); t.async_wait(print); //开始取票排队
cout<<"Main fun..."<<endl; //主线程该干嘛干嘛
io.run(); return 0; } //先输出 "Main fun..." 过5秒输出 "Hello,world!"
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& error,boost::asio::deadline_timer* t,int* count) { if(*count < 5) { std::cout<< *count << "\n"; ++(*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<<"\n"; return 0; }
//每隔一秒分别输出 0,1,2,3,4 最后输出 "Final count is 5"