阻塞等待:这里会等待3秒然后才进行输出。
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> int main(void) { boost::asio::io_service io; boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3)); timer.wait(); std::cout << "this is blocking wait" << std::endl; system("pause"); return 0; }
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> void print(const boost::system::error_code & e) { std::cout << "hello, world" << std::endl; } int main(void) { boost::asio::io_service io; boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3)); timer.async_wait(&print); std::cout << "this is asynchronous wait" << std::endl; // sleep(5); io.run(); system("pause"); return 0; }
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/bind.hpp> #include <windows.h> unsigned int start_t, end_t; void print(const boost::system::error_code& e, boost::asio::deadline_timer* timer, int* count) { if (*count < 5) { std::cout << "count: " << *count << std::endl; end_t = ::GetTickCount(); std::cout << "elapse time:" << end_t-start_t << std::endl; ++(*count); //timer->expires_from_now(boost::posix_time::seconds(1)); timer->expires_at(timer->expires_at() + boost::posix_time::seconds(1)); timer->async_wait(boost::bind(print, boost::asio::placeholders::error, timer, count)); } } int main() { int count = 0; boost::asio::io_service io; boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1)); timer.async_wait(boost::bind(print, boost::asio::placeholders::error, &timer, &count)); start_t = ::GetTickCount(); io.run(); std::cout << "run end" << std::endl; system("pause"); return 0; }
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/bind.hpp> class Printer { public: Printer(boost::asio::io_service& io) : count_(0), timer_(io, boost::posix_time::seconds(1)) { timer_.async_wait(boost::bind(&Printer::print, this)); } ~Printer() { } void print() { if (count_ < 5) { std::cout << "count: " << count_ << std::endl; ++count_; timer_.expires_from_now(boost::posix_time::seconds(1)); timer_.async_wait(boost::bind(&Printer::print, this)); } } private: int count_; boost::asio::deadline_timer timer_; }; int main() { boost::asio::io_service io; Printer printer(io); io.run(); system("pause"); return 0; }