作了一個不到200行的事件驅動庫,基於c++11標準,header-only,跨平臺。沒有使用io複用api,採用promise/future實現。支持自定義事件,經過wake_up函數異步喚醒。寫這個庫的動機是想爲以前本身寫的日誌庫提供日誌回滾機制。c++
github:https://github.com/chloro-pn/...git
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
//run the event_pool. std::shared_ptr<event_pool> ev(new event_pool()); std::thread th([=]()->void { ev->run(); });
//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);
while (true) { char buf[1024]; gets(buf); if (buf[0] == 'q') { ev->stop(); // stop the event_pool. break; } eh->wake_up(); } th.join();
1.輕量級,200行源代碼,語言層面的跨平臺,基於c++11標準。promise
2.僅須要頭文件,即拿即用。安全