基于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. 补充测试。
相关文章
相关标签/搜索