博客轉載自:http://blog.csdn.net/yockie/article/details/40386145
先跟着boost文檔中asio章節的指南中的幾個例子學習一下使用:
所有的Asio類只要簡單的包含"asio.hpp"頭文件便可使用:#include <boost/asio.hpp>
因為本程序中使用了定時器,我們需要包含相應的的Boost.Date_Time 頭文件來處理時間操作:
使用Asio的所有程序都至少需要一個提供訪問I/O功能的io_service 對象。因此在主函數中我們做的第一件事就是聲明一個這個類型的對象:boost::asio::io_service io;
接下來我們聲明一個boost::asio::deadline_timer類型的對象。作為 Asio的核心類,它提供的I/O功能(在此為定時器功能)通常用一個io_service 的引用作為其構造函數的第一個參數。第二個參數設置一個從現在開始5秒后終止的定時器。
boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
可以看一下boost::asio::deadline_timer的幾個構造函數:
basic_deadline_timer( boost::asio::io_service & io_service); basic_deadline_timer( boost::asio::io_service & io_service, const time_type & expiry_time); basic_deadline_timer( boost::asio::io_service & io_service, const duration_type & expiry_time);
注意后兩種的區別,說明以下2種用法是等價的:
boost::asio::deadline_timer t(io, boost::posix_time::microsec_clock::universal_time()+boost::posix_time::seconds(5)); boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
在這個簡單的程序中,我們用定時器演示一個阻塞等待。
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> int main() { boost::asio::io_service io; boost::asio::deadline_timer t(io, boost::posix_time::seconds(5)); t.wait(); std::cout << "Hello, world!\n"; return 0; }
deadline_timer::wait() 函數調用直到定時器終止(從定時器被創建算起,五秒后終止)才會返回。一個deadline timer 通常是下面兩種狀態中的一種:"expired(終止)" 或"not expired(不終止)"。
如果deadline_timer::wait() 函數被一個已經終止的定時器調用, 它將立即返回。
2. Timer.2 - 使用異步定時器
本例使用Asio的異步回調功能在定時器中演示一個異步等待。
使用Asio的異步功能意味着當一個異步操作完成時一個回調函數將被調用。在本程序中我們定義一個名為print 的函數,在異步等待結束后這個函數將被調用,
最后我們打印出 "Hello, world!" 信息以顯示定時器已經終止。
void print(const boost::system::error_code& /*e*/) { std::cout << "Hello, world!\n"; } int main() { boost::asio::io_service io; boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
接下來,我們調用 deadline_timer::async_wait() 函數執行一個異步等待去取代Timer.1例中的阻塞等待。當調用這個函數時我們傳入上面定義的print回調句柄。
t.async_wait(print);
最后,我們必須在io_service對象上調用io_service::run()成員函數。
Asio保證回調句柄僅僅能被io_service::run()啟動的當前線程所調用。 因此,如果io_service::run() 函數不執行,用於異步等待完成時的回調函數將永遠不會被調用。
當仍舊有“工作”可做時,io_service::run() 函數會繼續運行。在本例中,“工作”是定時器的異步等待,因此,直到定時器終止和回調函數執行完成,程序才會返回。
在調用io_service::run()之前確保給 io_service 一些工作去做,這非常重要。 例如,如果我們省略了上面調用的deadline_timer::async_wait() 函數,io_service對象將沒有任何事情去做,因此io_service::run() 將立即返回。
和同步方式相比,它主要有兩點不同:
(1) 調用的是非阻塞函數async_wait,它的入參是一個回調函數。
(2) 顯式調用io_service.run()函數驅動異步IO調度。
值得提出的是,異步回調函數handler的參數中有一個error,注意這個error很重要,表明這個handler是因為超時被執行還是因為被cancel。
符合2種情況之一,handler被執行:超時或者被cancel(可以通過此error的值進行區分)。這同時隱含的說明了除非io.stop被調用,否則handler一定會被執行。即便是被cancel。
被cancel有多種方法,直接調用cancel或者調用expires_at,expires_from_now重新設置超時時間。
#include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; void Print(const boost::system::error_code &ec) { cout<<"Hello World!"<<endl; cout<<boost::this_thread::get_id()<<endl; } int main() { cout<<boost::this_thread::get_id()<<endl; boost::asio::io_service io; boost::asio::deadline_timer t(io, boost::posix_time::seconds(5)); t.async_wait(Print); cout<<"to run"<<endl; io.run(); cout<<"exit"<<endl; return 0; }
結果: 2f98 to run (此處等了5s) Hello World! 2f98 (說明是同一線程) exit
3. 回調函數綁定參數
本例使定時器每秒被激活一次。例子將示范如何給你的函數指針傳遞附加參數。
使用Asio實現一個重復定時器,你必須在你的回調函數中去改變定時器的終止時間,然后開始一個新的異步等待。顯然這意味着回調函數必須擁有改變定時器對象的權限。為此我們為 print函數增加兩個新參數:
(1) 一個指向定時器對象的指針。
(2) 一個用於當定時器第6次被激活時我們可以中止程序的計數器。
void print(const boost::system::error_code& /*e*/,boost::asio::deadline_timer* t, int* count) {
if (*count < 5) { std::cout << *count << "\n"; ++(*count)
} }
如上所示,示例程序使用了一個計數器,當定時器被第6次激活時,用來中止程序。然而,你將看到這里並沒有顯式地要求io_service對象中止。回憶示例2中,當沒有更多“工作”去做時,io_service::run() 函數完成。在計數器達到 5時,定時器並沒有啟動一個新的異步等待。該io_service執行完工作后停止運行。
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
接着,我們推遲定時器的終止時間。通過在原先的終止時間上增加延時,我們可以確保定時器不會在處理回調函數所需時間內到期。
接着我們在定時器中啟動一個新的異步等待。我們必須使用boost::bind() 函數給你的回調函數綁定額外的參數,因為deadline_timer::async_wait() 函數只期望得到一個擁用 void(const boost::system::error_code&) 簽名的函數指針(或函數對象)。為你的print函數綁定附加的參數后,它就成為與簽名精確匹配的函數對象。
在本例中,boost::bind()的boost::asio::placeholders::error參數是為了給回調函數傳入一個error對象。當開始異步操作時,如果使用boost::bind(),你必須指定和回調函數的參數列表相匹配的一個參數。在示例4中,如果在回調函數中,這個參數不是必需的,這個占位符會被省略。
t->async_wait(boost::bind(print,boost::asio::placeholders::error, t, count));
#include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; void Print(const boost::system::error_code &ec, boost::asio::deadline_timer* pt, int * pcount) { if (*pcount < 3) { cout<<"count = "<<*pcount<<endl; cout<<boost::this_thread::get_id()<<endl; (*pcount) ++; pt->expires_at(pt->expires_at() + boost::posix_time::seconds(5)) ; pt->async_wait(boost::bind(Print, boost::asio::placeholders::error, pt, pcount)); } } int main() { cout<<boost::this_thread::get_id()<<endl; boost::asio::io_service io; boost::asio::deadline_timer t(io, boost::posix_time::seconds(5)); int count = 0; t.async_wait(boost::bind(Print, boost::asio::placeholders::error, &t, &count)); cout<<"to run"<<endl; io.run(); cout << "Final count is " << count << "\n"; cout<<"exit"<<endl; return 0; }
結果: 14d0 to run (等了5s) count = 0 14d0 (等了5s) count = 1 14d0 (等了5s) count = 2 14d0 (等了5s) Final count is 3 exit
4. 多線程同步回調
本例示范了使用boost::asio::strand 類來創建多線程程序中的同步回調句柄。
前幾個例程只是在單線程下使用io_service::run() 函數來避免處理函同步。 如你所見,Asio庫保證回調句柄僅能被當前正在調用 io_service::run(). 函數的線程調用。 因此,在單線程中調用io_service::run() 能確保回調句柄不被並發運行。
下面是Asio在單線程程序中的局限性,尤其是服務器方面,包括:
(1)操作需要較長時間處理才能完成時弱響應。
(1)在大規模的多處理機系統中表現不佳。
如果你發現自己陷入這些局限時,一個可供選擇的方法是創建一個每個線程都調用io_service::run() 的線程池。 不過,因為這允許並發操作,當訪問一個共享、非線程安全的資源時,我們需要一個同步方式。
讓我們從定義一個名為printer的類開始,這與前一個示例中的類很相似。這個類是上一個例子的擴展,這里我們使用兩個並行的定時器。
class CPrinter
除了初始化一對boost::asio::deadline_timer 成員變量外,構造函數還初始化一個boost::asio::strand類型strand_ 成員變量。
boost::asio::strand 對象保證:對於通過它來分派執行的眾操作中,只有一個操作執行完成之后才允許進入下一個操作。 這種保證與多少個線程調用io_service::run() 無關。當然,如果不是通過一個boost::asio::strand對象分派, 或者通過其它不同的boost::asio::strand對象分派,這些操作仍舊可能是並發的。
CPrinter(boost::asio::io_service &io) :m_strand(io) ,m_timer1(io, boost::posix_time::seconds(5)) ,m_timer2(io, boost::posix_time::seconds(5)) ,m_count(0) { m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this) )); m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this) )); } ~CPrinter() { cout<<"m_count = "<<m_count<<endl; }
當開始同步操作時,每一個回調句柄都使用boost::asio::strand對象進行“包裝”。strand::wrap() 函數返回一個新的通過boost::asio::strand對象自動分派的內部句柄。 通過同一boost::asio::strand對象對句柄進行“ 包裝”,我們可以保證操作不會並發執行。
在一個多線程程序中,當訪問同一共享資源時,異步操作必須是同步的。在本例中,print1 和print2)函數使用的共享資源std::cout 和count_數據成員。
void Print1() { if (m_count < 10) { cout<<"Timer1 count = "<<m_count<<endl; cout<<boost::this_thread::get_id()<<endl; m_count++; m_timer1.expires_at(m_timer1.expires_at() + boost::posix_time::seconds(1)) ; m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this) ) ); } } void Print2() { if (m_count < 10) { cout<<"Timer2 count = "<<m_count<<endl; cout<<boost::this_thread::get_id()<<endl; m_count++; m_timer2.expires_at(m_timer2.expires_at() + boost::posix_time::seconds(1)) ; m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this) ) ); } }
main函數中, io_service::run() 現在被兩個線程調用:主線程和一個附加線程。這一切依賴於boost::thread對象來完成。
正如它被一個單線程調用一樣,io_service::run()的並發調用會一直持續到無任何“工作”可做。后台線程直到所有異步操作都完成后才會退出。
#include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace std; class CPrinter { public: CPrinter(boost::asio::io_service &io) :m_strand(io) ,m_timer1(io, boost::posix_time::seconds(5)) ,m_timer2(io, boost::posix_time::seconds(5)) ,m_count(0) { m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this) ) ); m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this) ) ); } ~CPrinter() { cout<<"m_count = "<<m_count<<endl; } void Print1() { if (m_count < 10) { cout<<"Timer1 count = "<<m_count<<endl; cout<<boost::this_thread::get_id()<<endl; m_count++; m_timer1.expires_at(m_timer1.expires_at() + boost::posix_time::seconds(1)) ; m_timer1.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print1, this) ) ); } } void Print2() { if (m_count < 10) { cout<<"Timer2 count = "<<m_count<<endl; cout<<boost::this_thread::get_id()<<endl; m_count++; m_timer2.expires_at(m_timer2.expires_at() + boost::posix_time::seconds(1)) ; m_timer2.async_wait(m_strand.wrap(boost::bind(&CPrinter::Print2, this) ) ); } } private: boost::asio::strand m_strand; boost::asio::deadline_timer m_timer1; boost::asio::deadline_timer m_timer2; int m_count; }; int main() { cout<<boost::this_thread::get_id()<<endl; boost::asio::io_service io; CPrinter cp(io); cout<<"to run"<<endl; boost::thread td(boost::bind(&boost::asio::io_service::run, &io)); io.run(); cout<<"exit"<<endl; return 0;
運行結果
620c to run Timer2 count = 0 79c4 Timer1 count = 1 620c Timer1 count = 2 620c Timer2 count = 3 79c4 Timer2 count = 4 79c4 Timer1 count = 5 620c Timer1 count = 6 620c Timer2 count = 7 79c4 Timer2 count = 8 79c4 Timer1 count = 9 620c exit m_count = 10
說明:
(1)兩個Timer確實是在不同線程中執行,並且只有一個print操作執行完成之后才允許進入另一個print操作
(2)Timer1始終在一個線程中執行,Timer2始終在另一個線程中執行,(但不一定就是Timer1在主線程執行,這個分配時隨機的)
注意:
deadline_timer和socket一樣,都用io_service作為構造函數的參數。在其上進行異步操作,都將導致和io_service所包含的iocp相關聯。這同樣意味着在析構 io_service之前,必須析構關聯在這個io_service上的deadline_timer。
引申:
關於boost::asio::strand,有三個函數:post, dispatch, wrap
post: 不管什么情況都會把任務丟到隊列中,然后立即返回。如:m_strand.post(boost::bind(print, 2));
dispatch: 如果跟run()在一個線程,那么任務會直接在dispatch內部調用,執行結束后返回。不在一個線程跟post一樣。如:m_strand.dispatch(boost::bind(print, 1));
wrap:返回一個新的通過boost::asio::strand對象自動分派的內部句柄
參考:《boost技術文檔》