libevent个人理解

1、利用了前置声明来在c语言的基础上进行封装操作。即在include目录下防止event.h等头文件,在这些头文件中只暴露struct的声明却不暴露其定义,对于如event_base等结构的操作均使用封装的函数进行,而这些封装的函数则定义在event.c中,event.c会包含event.h和event-internal.h,带有internal后缀的头文件才包含了这些结构体的实际定义。这样保证了外部操作不会污染内部结构体的内部数据,实现了封装的效果。

2、Libevent支持多种I/O多路复用技术的关键就在于结构体eventop,这个结构体前面也曾提到过,它的成员是一系列的函数指针, 定义在event-internal.h文件中:

 1 struct eventop {  
 2     const char *name;  
 3     void *(*init)(struct event_base *); // 初始化  
 4     int (*add)(void *, struct event *); // 注册事件  
 5     int (*del)(void *, struct event *); // 删除事件  
 6     int (*dispatch)(struct event_base *, void *, struct timeval *); // 事件分发  
 7     void (*dealloc)(struct event_base *, void *); // 注销,释放资源  
 8     /* set if we need to reinitialize the event base */  
 9     int need_reinit;  
10 };  

在libevent中,每种I/O demultiplex机制的实现都必须提供这五个函数接口,来完成自身的初始化、销毁释放;对事件的注册、注销和分发。
比如对于epoll,libevent实现了5个对应的接口函数,并在初始化时并将eventop的5个函数指针指向这5个函数,那么程序就可以使用epoll作为I/O demultiplex机制了。这样利用函数指针的方式实现了多态。详细介绍

关于libevent的详细介绍专栏

原文地址:https://www.cnblogs.com/zl1991/p/7987109.html