阅读Libevent网络库

不能不学习啊

Posted by 大狗 on December 8, 2020

阅读Libevent/libuv源码

前言

libevent 阅读的文档是:

  • 这篇讲的很简陋https://github.com/libevent/libevent.git
  • 讲的很不错的文档:https://github.com/balloonwj/CppGuide/tree/master/articles/libevent%E6%BA%90%E7%A0%81%E6%B7%B1%E5%BA%A6%E5%89%96%E6%9E%90
  • 官方文档:http://www.wangafu.net/~nickm/libevent-book/
  • 这篇入门文档讲的很不错http://senlinzhan.github.io/2017/08/12/libevent/

libevent是reactor模式代码的静态库,使用的时候需要先将reactor即struct event_base *event_base_new(void);初始化,然后初始化对应的event并挂到event_base上,然后执行的线程再执行event_base_loop不断检索是否有注册事件触发,如果有事件再调用相应的回调并触发。需要注意的是,eventloop只能在一个线程执行检查是否有事件ready的loop,如果想多线程执行loop只能每个线程一个eventbase。event_base_dispatch()event_base_loop()一样,只不过没设置flag。Thus, it keeps running until there are no more registered events or until event_base_loopbreak() or event_base_loopexit() is called.

#define EVLOOP_ONCE             0x01    //event_base_loop会等待激活事件,然后处理当前批次的激活事件,然后返回,也就是说只执行一次
#define EVLOOP_NONBLOCK         0x02		//event_base_loop不会等待激活事件,而是每次执行的时候检查是不是有事情就绪,如果有就执行相对应事件的回调函数。完成工作后,如果正常退出, event_base_loop()返回0;如果因为后端中的某些未处理 错误而退出,则返回 -1。
#define EVLOOP_NO_EXIT_ON_EMPTY 0x04

int event_base_loop(struct event_base *base, int flags) {
	while (any events are registered with the loop, or EVLOOP_NO_EXIT_ON_EMPTY was set) {
    if (EVLOOP_NONBLOCK was set, or any events are already active)
        If any registered events have triggered, mark them active.
    else
        Wait until at least one event has triggered, and mark it active.

    for (p = 0; p < n_priorities; ++p) {
       if (any event with priority of p is active) {
          Run all active events with priority of p.
          break; /* Do not run any events of a less important priority */
       }
    }

    if (EVLOOP_ONCE was set or EVLOOP_NONBLOCK was set)
       break;
	}
}

具体的操作对象是struct event,Events have similar lifecycles. Once you call a Libevent function to set up an event and associate it with an event base, it becomes initialized. At this point, you can add, which makes it pending in the base. When the event is pending, if the conditions that would trigger an event occur (e.g., its file descriptor changes state or its timeout expires), the event becomes active, and its (user-provided) callback function is run. If the event is configured persistent, it remains pending. If it is not persistent, it stops being pending when its callback runs. You can make a pending event non-pending by deleting it, and you can add a non-pending event to make it pending again。

libuv的文档为:

  • https://luohaha.github.io/Chinese-uvbook/source/introduction.html 中文文档
  • http://docs.libuv.org/en/v1.x/ 官方文档

结尾

唉,尴尬

狗头的赞赏码.jpg