1.定時器的使用,sleep是等待線程,asio封裝了操作系統的異步系統調用select,epoll.
io_servie 實現了一個任務隊列,這里的任務就是void(void)的函數。Io_servie最常用的兩個接口是post和run,post向任務隊列中投遞任務,run是執行隊列中的任務,直到全部執行完畢,並且run可以被N個線程調用。Io_service是完全線程安全的隊列。
#include <iostream> #include <string> #include <vector> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::asio; using namespace boost; int main() { io_service ios; deadline_timer t(ios,posix_time::seconds(2)); cout << t.expires_at() <<endl; t.wait(); cout << "hello asio" <<endl; return 0; }
2.定時器的作用是類似sendto,recvfrom等IO操作,相當於等待一段時間有數據到達,而io_service的作用類似select,服務於IO。
異步I/O調用
#include <iostream> #include <string> #include <vector> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; using namespace boost::asio; using namespace boost; void print(const system::error_code&) { cout << "hello asio" <<endl; } int main() { io_service ios; deadline_timer t(ios,posix_time::seconds(2)); t.async_wait(print); cout << "it show before t exired" <<endl; ios.run(); return 0; }