有过看nginx源码的基础,现在来看libevent源码,感觉要轻松多了。。
第一篇文章,主要是还是介绍一些几个重要的数据结构吧。。。。
首先是event结构:
struct event {
TAILQ_ENTRY (event) ev_next; //用于构成event的双向链表
TAILQ_ENTRY (event) ev_active_next;
TAILQ_ENTRY (event) ev_signal_next;
unsigned int min_heap_idx; /* for managing timeouts */ //小根堆,主要是用于定时事件
struct event_base *ev_base; //所属的eventbase结构
int ev_fd; //关联的文件描述符
short ev_events; //关心的事件类型
short ev_ncalls; //回调函数执行的次数
short *ev_pncalls; /* Allows deletes in callback */
struct timeval ev_timeout; //超时
int ev_pri; /* smaller numbers are higher priority *///优先级
void (*ev_callback)(int, short, void *arg); //事件的回调函数
void *ev_arg; //自定义的数据
int ev_res; /* result passed to event callback */
int ev_flags; //表明当前event的状态
};
至于每一个字段是干嘛用的基本上都标明出来了,libevent定义的事件类型如下:
#define EV_TIMEOUT 0x01
#define EV_READ 0x02
#define EV_WRITE 0x04
#define EV_SIGNAL 0x08
#define EV_PERSIST 0x10 /* Persistant event */
定义的事件状态如下:
#define EVLIST_TIMEOUT 0x01 //事件在堆中
#define EVLIST_INSERTED 0x02 //时间已经注册到链表当中
#define EVLIST_SIGNAL 0x04 //
#define EVLIST_ACTIVE 0x08 //时间在激活链表中
#define EVLIST_INTERNAL 0x10
#define EVLIST_INIT 0x80 //event已经初始化
好了,接下来来看另外一个结构的定义:
struct eventop {
const char *name; //Ãû×Ö
void *(*init)(struct event_base *); //¾ßÌåµÄʼþÄ£¿éµÄ³õʼ»¯º¯Êý
int (*add)(void *, struct event *); //ʼþÄ£¿éµÄ¾ßÌåµÄÌí¼Óʼþ
int (*del)(void *, struct event *); //ɾ³ýʼþ
int (*dispatch)(struct event_base *, void *, struct timeval *); //ʼþÑ»·
void (*dealloc)(struct event_base *, void *); //ÊÍ·Å×ÊÔ´
/* set if we need to reinitialize the event base */
int need_reinit;
};
如果读过nginx源码,那么将会对它非常的熟悉,因为libevent底层也支持不同的事件类型,如epoll等,这里全是函数指针,就指向他们的一些具体的实现函数。。。。
接下来也是一个非常重要的定义:
struct event_base {
const struct eventop *evsel;
void *evbase;
int event_count; /* counts number of total events */
int event_count_active; /* counts number of active events */
int event_gotterm; /* Set to terminate loop */
int event_break; /* Set to terminate loop immediately */
/* active event management */
struct event_list **activequeues; //二级指针,因为支持优先级
int nactivequeues;
/* signal handling info */
struct evsignal_info sig; //管理信号
struct event_list eventqueue;
struct timeval event_tv;
struct min_heap timeheap; //用于维护定时事件的小根堆
struct timeval tv_cache;
};
这个是整个libevent的核心结构,因为所有的操作都离不开他,基本上每个申明的作用一看也能看出来,就不细细讲了。
好了,重要的结构定义就先介绍到这里。。。