基於c++11的event-driven library。

作了一個不到200行的事件驅動庫,基於c++11標準,header-only,跨平臺。沒有使用io複用api,採用promise/future實現。支持自定義事件,經過wake_up函數異步喚醒。寫這個庫的動機是想爲以前本身寫的日誌庫提供日誌回滾機制。c++

github:https://github.com/chloro-pn/...git

event_pool

基本介紹

a header-only event-driven library based on c++11,which uses std::promise/std::future asyn-model.github

一個基於c++11標準,僅須要頭文件的事件驅動庫:),使用std::promise/std::future異步模型實現。api

使用方法:

  • 建立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();

使用指南:

  1. 全部對象均需使用std::shared_ptr建立。
  2. 每一個time_handle對象和event_handle對象只能push進一個event_pool對象。
  3. event_handle對象可設置兩種類型:every和once,every類型容許不限次數的wake_up,event_pool會處理每次wake_up,而once類型只能被喚醒一次,但容許屢次調用wake_up函數(線程安全),這意味着能夠在多個線程併發的觸發事件。
  4. time_handle對象可設置兩種類型:duration和time_point,其中duration類型經過設置duration_成員來指定今後刻開始,每間隔多少時間就觸發一次。time_point類型經過設置time_point_成員來指定在哪一個時刻僅觸發一次。
  5. 回調函數的輸入參數就是該事件對象自己,你能夠經過其訪問設置的id_,type_,args_等等。
  6. event_pool的run函數能夠在多個線程併發執行(maybe?),這一點暫且不保證。

特色:

1.輕量級,200行源代碼,語言層面的跨平臺,基於c++11標準。promise

2.僅須要頭文件,即拿即用。安全

todo:

  1. 定義更便於使用,減小出錯機率的接口。
  2. 補充測試。
相關文章
相關標籤/搜索