libevent源代码之c实现多态
读libevent源代码,有几点体会,记录如下,希望猎头看到,赶紧来挖我啊。
1、libevent源代码是用c语言写的,但是通过结构体实现了c++中的多态,叹为观止。具体介绍如下:
struct eventop {
const char *name;
void *(*init)(struct event_base *);
int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
int (*dispatch)(struct event_base *, struct timeval *);
void (*dealloc)(struct event_base *);
int need_reinit;
enum event_method_feature features;
size_t fdinfo_len;
};
这个结构体,结构体里定义了函数指针。包括初始化、添加删除和dispatch等操作。Io的操作被封装为该结构体。具体的实现以epoll操作为例
static const struct eventop epollops_changelist = {
"epoll (with changelist)",
epoll_init,
event_changelist_add,
event_changelist_del,
epoll_dispatch,
epoll_dealloc,
1, /* need reinit */
EV_FEATURE_ET|EV_FEATURE_O1,
EVENT_CHANGELIST_FDINFO_SIZE
};
定义实现了这几个函数。这个结构体相当于基类,即可以理解为定义了这样一个基类:
class eventop
{
string name;
virtual void *Init(struct event_base *) = 0;
virtual int add(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
virtual int del(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
virtual int dispatch(struct event_base *, struct timeval *);
virtual void dealloc(struct event_base *);
};
然后epoll继承该基类,实现具体的操作。通过该结构体,代码把epoll和evsignal和equeue等抽象为一个对象。简化了代码的逻辑
浙公网安备 33010602011771号