基於c++11的event-driven library的理解
阿新 • • 發佈:2020-02-13
做了一個不到200行的事件驅動庫,基於c++11標準,header-only,跨平臺。支援自定義事件,通過wake_up函式非同步喚醒。寫這個庫的動機是想為之前自己寫的日誌庫提供日誌回滾機制。
github:https://github.com/chloro-pn/event_pool
event_pool
基本介紹
a header-only event-driven library based on c++11.
一個基於c++11標準,僅需要標頭檔案的事件驅動庫:)。
使用方法:
建立event_pool物件並申請一個執行緒做事件處理,在該執行緒中呼叫run函式。
//run the event_pool. std::shared_ptr<event_pool> ev(new event_pool()); std::thread th([=]()->void { ev->run(); });
建立event_handle和time_handle物件並設定id_,type_,回撥函式func_,上下文args_(如果是time_handle則還要設定觸發時間)等,push進event_pool物件。
//create time_handle. std::shared_ptr<time_handle> h(new time_handle()); h->id_ = "timer test "; h->type_ = time_handle::type::duration; h->duration_ = seconds(2); h->args_ = nullptr; h->func_ = [](std::shared_ptr<time_handle> self)->void { std::cout << self->id_ << " wake up !" << std::endl; }; //create event_handle. std::shared_ptr<event_handle> eh(new event_handle()); eh->id_ = "back cout "; eh->type_ = event_handle::type::every; eh->args_ = nullptr; eh->func_ = [](std::shared_ptr<event_handle> self)->void { std::cout << self->id_ << " wake up !"<<std::endl; }; //push them into ev. ev->push_timer(h); ev->push_event(eh);
在需要觸發事件的時候呼叫wake_up函式(time_handle沒有wake_up函式,等待時間到達自動觸發)。當需要關閉event_pool時,呼叫stop函式,然後回收執行緒,沒有來得及處理的事件會被丟棄,即使當event_pool 物件完全銷燬後,仍然可以呼叫wake_up函式,此時會直接返回。
while (true) { char buf[1024]; gets(buf); if (buf[0] == 'q') { ev->stop(); // stop the event_pool. break; } eh->wake_up(); } th.join();
使用指南:
- 所有物件均需使用std::shared_ptr建立。
- 每個time_handle物件和event_handle物件只能push進一個event_pool物件。
- event_handle物件可設定兩種型別:every和once,every型別允許不限次數的wake_up,event_pool會處理每次wake_up,而once型別只能被喚醒一次,但允許多次呼叫wake_up函式(執行緒安全),這意味著可以在多個執行緒併發的觸發事件。
- time_handle物件可設定兩種型別:duration和time_point,其中duration型別通過設定duration_成員來指定從此刻開始,每間隔多少時間就觸發一次。time_point型別通過設定time_point_成員來指定在哪個時刻僅觸發一次。
- 回撥函式的輸入引數就是該事件物件本身,你可以通過其訪問設定的id_,type_,args_等等。
- event_pool的run函式可以在多個執行緒併發執行(maybe?),這一點暫且不保證。
特點:
1.輕量級,200行原始碼,語言層面的跨平臺,基於c++11標準。
2.僅需要標頭檔案,即拿即用。
todo:
- 定義更便於使用,減少出錯概率的介面。
- 補充測試。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。