libevent项目分析 (二) -- I/O多路复用基础 .事件驱动

http://blog.csdn.net/xplizm/article/details/7277588

前言

分析libevent库就不得不先了解I/O多路复用技术,这是Reactor模式实现的基础,而Reactor模式是libevent库的核心内容。 

那么何为I/O多路复用技术?  可以参考http://blog.163.com/xychenbaihu@yeah/blog/static/13222965520112163171778/的介绍,我个人理解所谓I/O多路复用技术,简单地说就是当应用中要“同时”监视多个I/O描述符状态(可读,可写,异常)的时候,不需要在应用层分别对每个I/O描述符调用I/O操作函数(read, write)进行监视和处理,而是将这些描述符按照监视状态设置成集合,通过一次系统调用实现。借用《UNIX网络编程》第一卷 第6章的说明就是:如果一个或多个I/O条件满足(例如,输入已经准备好被读,或者描述符字可以承接更多的输出)时,我们就被通知到,这个能力被称为I/O复用。 I/O复用典型地用在下列网络应用场合:

  1. 当客户处理多个描述符字时(一般是交互式输入和网络套接口)
  2. 一个客户同时处理多个套接口时可能的,但很少出现
  3. 如果一个TCP服务器即要处理监听套接口,又要处理已链接套接口
  4. 如果一个服务器即要处理TCP,又要处理UDP
  5. 如果一个服务器要处理多个服务或者多个协议

第一篇已经介绍了libevent支持的I/O多路复用技术有select/poll/epoll,先从最传统的select函数开始分析。

select函数定义

select是一种同步的I/O多路复用函数,该函数允许进程指示内核等待多个事件中的任一个发生,并仅在一个或多个事件发生或经过某指定的时间后才唤醒进程。所谓同步I/O是区别于异步I/O,即select函数返回要么是因为有错误产生或者超时返回,要么是因为监视的句柄状态就绪,否则该函数会阻塞。关于I/O模型的说明可以参考一下http://www.ibm.com/developerworks/cn/linux/l-async/

在linux环境下man select可以得到该函数的帮助信息如下:

       /* According to POSIX.1-2001 */
       #include <sys/select.h>

       /* According to earlier standards */
       #include <sys/time.h>
       #include <sys/types.h>
       #include <unistd.h>

       int select(int nfds, fd_set *readfds, fd_set *writefds,
                  fd_set *exceptfds, struct timeval *timeout);


参数说明
ndfs: select函数参数中三个描述符集中找出最高描述符编号值,然后加1
readfds: select函数监视的可读描述符集合
writefds: select函数监视的可写描述符集合
exceptfds: select函数监视的异常描述符集合
timeout: select函数超时结束时间(timeout == NULL表示永久等待; timeout->tv_sec ==0 && timeout->tv_usec == 0表示完全不等待,测试所有指定的描述符并立即返回)


返回值说明

       -1 : 有错误产生

        0 : 表示select函数超时返回,且函数监视的可读、可写、异常描述符集合无事件发生

      >0 : 表示select函数成功返回,返回值为已经准备好描述符的正数目,且三个描述符集合中仍旧打开的位是对应于已经准备好的描述符位


描述符集合操作相关的函数

       void FD_CLR(int fd, fd_set *set);
       int    FD_ISSET(int fd, fd_set *set);
       void FD_SET(int fd, fd_set *set);
       void FD_ZERO(fd_set *set);


libevent库中select I/O复用技术的实现

libevent支持多种I/O多路复用技术,这些技术的实现是通过eventop这个结构来抽象的(非常巧妙,C也能实现类似C++的多态),其定义如下:

  1. /** Structure to define the backend of a given event_base. */  
  2. struct eventop {  
  3.     /** The name of this backend. */  
  4.     const char *name;  
  5.     /** Function to set up an event_base to use this backend.  It should 
  6.      * create a new structure holding whatever information is needed to 
  7.      * run the backend, and return it.  The returned pointer will get 
  8.      * stored by event_init into the event_base.evbase field.  On failure, 
  9.      * this function should return NULL. */  
  10.     void *(*init)(struct event_base *);  
  11.     /** Enable reading/writing on a given fd or signal.  'events' will be 
  12.      * the events that we're trying to enable: one or more of EV_READ, 
  13.      * EV_WRITE, EV_SIGNAL, and EV_ET.  'old' will be those events that 
  14.      * were enabled on this fd previously.  'fdinfo' will be a structure 
  15.      * associated with the fd by the evmap; its size is defined by the 
  16.      * fdinfo field below.  It will be set to 0 the first time the fd is 
  17.      * added.  The function should return 0 on success and -1 on error. 
  18.      */  
  19.     int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);  
  20.     /** As "add", except 'events' contains the events we mean to disable. */  
  21.     int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);  
  22.     /** Function to implement the core of an event loop.  It must see which 
  23.         added events are ready, and cause event_active to be called for each 
  24.         active event (usually via event_io_active or such).  It should 
  25.         return 0 on success and -1 on error. 
  26.      */  
  27.     int (*dispatch)(struct event_base *, struct timeval *);  
  28.     /** Function to clean up and free our data from the event_base. */  
  29.     void (*dealloc)(struct event_base *);  
  30.     /** Flag: set if we need to reinitialize the event base after we fork. 
  31.      */  
  32.     int need_reinit;  
  33.     /** Bit-array of supported event_method_features that this backend can 
  34.      * provide. */  
  35.     enum event_method_feature features;  
  36.     /** Length of the extra information we should record for each fd that 
  37.         has one or more active events.  This information is recorded 
  38.         as part of the evmap entry for each fd, and passed as an argument 
  39.         to the add and del functions above. 
  40.      */  
  41.     size_t fdinfo_len;  
  42. };  
/** Structure to define the backend of a given event_base. */
struct eventop {
	/** The name of this backend. */
	const char *name;
	/** Function to set up an event_base to use this backend.  It should
	 * create a new structure holding whatever information is needed to
	 * run the backend, and return it.  The returned pointer will get
	 * stored by event_init into the event_base.evbase field.  On failure,
	 * this function should return NULL. */
	void *(*init)(struct event_base *);
	/** Enable reading/writing on a given fd or signal.  'events' will be
	 * the events that we're trying to enable: one or more of EV_READ,
	 * EV_WRITE, EV_SIGNAL, and EV_ET.  'old' will be those events that
	 * were enabled on this fd previously.  'fdinfo' will be a structure
	 * associated with the fd by the evmap; its size is defined by the
	 * fdinfo field below.  It will be set to 0 the first time the fd is
	 * added.  The function should return 0 on success and -1 on error.
	 */
	int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
	/** As "add", except 'events' contains the events we mean to disable. */
	int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
	/** Function to implement the core of an event loop.  It must see which
	    added events are ready, and cause event_active to be called for each
	    active event (usually via event_io_active or such).  It should
	    return 0 on success and -1 on error.
	 */
	int (*dispatch)(struct event_base *, struct timeval *);
	/** Function to clean up and free our data from the event_base. */
	void (*dealloc)(struct event_base *);
	/** Flag: set if we need to reinitialize the event base after we fork.
	 */
	int need_reinit;
	/** Bit-array of supported event_method_features that this backend can
	 * provide. */
	enum event_method_feature features;
	/** Length of the extra information we should record for each fd that
	    has one or more active events.  This information is recorded
	    as part of the evmap entry for each fd, and passed as an argument
	    to the add and del functions above.
	 */
	size_t fdinfo_len;
};


 

具体到select I/O多路复用的实现定义如下:

  1. const struct eventop selectops = {  
  2.     "select",  
  3.     select_init,  
  4.     select_add,  
  5.     select_del,  
  6.     select_dispatch,  
  7.     select_dealloc,  
  8.     0, /* doesn't need reinit. */  
  9.     EV_FEATURE_FDS,  
  10.     0,  
  11. };  
const struct eventop selectops = {
	"select",
	select_init,
	select_add,
	select_del,
	select_dispatch,
	select_dealloc,
	0, /* doesn't need reinit. */
	EV_FEATURE_FDS,
	0,
};

libevent库的select封装

libevent库中对select的封装在Select.c文件中,其中selectop结构是对描述符数据的封装

  1. struct selectop {  
  2.     int event_fds;           /* Highest fd in fd set */  
  3.     int event_fdsz;              /* 描述符集的存储空间大小 */  
  4.     int resize_out_sets;         /* 标志位,在select_resize函数中对event_readset_in和event_writeset_in两个描述符集调整了存储空间后将该标志位置为1, 
  5. 在select_dispatch函数中对event_readset_out和event_writeset_out两个描述符集调整了存储空间后将该标志位置为0 */  
  6.     fd_set *event_readset_in;    /* select函数监视的读描述符集,用于select_add,select_del函数操作 */  
  7.     fd_set *event_writeset_in;   /* select函数监视的写描述符集,用于select_add,select_del函数操作 */  
  8.     fd_set *event_readset_out;   /* select函数监视的读描述符集,用于select函数调用操作 */  
  9.     fd_set *event_writeset_out;  /* select函数监视的读描述符集,用于select函数调用操作 */  
  10. };  
struct selectop {
	int event_fds;		     /* Highest fd in fd set */
	int event_fdsz;              /* 描述符集的存储空间大小 */
	int resize_out_sets;         /* 标志位,在select_resize函数中对event_readset_in和event_writeset_in两个描述符集调整了存储空间后将该标志位置为1,
在select_dispatch函数中对event_readset_out和event_writeset_out两个描述符集调整了存储空间后将该标志位置为0 */
	fd_set *event_readset_in;    /* select函数监视的读描述符集,用于select_add,select_del函数操作 */
	fd_set *event_writeset_in;   /* select函数监视的写描述符集,用于select_add,select_del函数操作 */
	fd_set *event_readset_out;   /* select函数监视的读描述符集,用于select函数调用操作 */
	fd_set *event_writeset_out;  /* select函数监视的读描述符集,用于select函数调用操作 */
};

如下几个函数主要是对描述符操作和select函数的封装

static void *select_init(struct event_base *);
static int select_add(struct event_base *, int, short old, short events, void*);
static int select_del(struct event_base *, int, short old, short events, void*);
static int select_dispatch(struct event_base *, struct timeval *);
static void select_dealloc(struct event_base *);


指定采用select

还是习惯通过例程的调试方法来分析上面select这几个相关函数的关系,但不幸的是Linux下默认的多路复用实现不是select,但Linux肯定是支持select,如何让例程采用select呢? 


在event_base_new_with_config函数中可以发现libevent选取多路复用机制的实现,按照eventtops中eventop的顺序检查,最先满足的eventop将被采用,所以如果要指定select,就必须把前面满足的项忽略掉

  1. for (i = 0; eventops[i] && !base->evbase; i++) {  
  2.     if (cfg != NULL) {  
  3.         /* determine if this backend should be avoided */  
  4.         if (event_config_is_avoided_method(cfg,  
  5.             eventops[i]->name))  
  6.             continue;  
  7.         if ((eventops[i]->features & cfg->require_features)  
  8.             != cfg->require_features)  
  9.             continue;  
  10.     }  
  11.   
  12.     /* also obey the environment variables */  
  13.     if (should_check_environment &&  
  14.         event_is_method_disabled(eventops[i]->name))  
  15.         continue;  
  16.   
  17.     base->evsel = eventops[i];  
  18.   
  19.     base->evbase = base->evsel->init(base);  
  20. }  
	for (i = 0; eventops[i] && !base->evbase; i++) {
		if (cfg != NULL) {
			/* determine if this backend should be avoided */
			if (event_config_is_avoided_method(cfg,
				eventops[i]->name))
				continue;
			if ((eventops[i]->features & cfg->require_features)
			    != cfg->require_features)
				continue;
		}

		/* also obey the environment variables */
		if (should_check_environment &&
		    event_is_method_disabled(eventops[i]->name))
			continue;

		base->evsel = eventops[i];

		base->evbase = base->evsel->init(base);
	}


而eventops定义的顺序如下:

  1. /* Array of backends in order of preference. */  
  2. static const struct eventop *eventops[] = {  
  3. #ifdef _EVENT_HAVE_EVENT_PORTS  
  4.     &evportops,  
  5. #endif  
  6. #ifdef _EVENT_HAVE_WORKING_KQUEUE  
  7.     &kqops,  
  8. #endif   
  9. #ifdef _EVENT_HAVE_EPOLL  
  10.     &epollops,  
  11. #endif  
  12. #ifdef _EVENT_HAVE_DEVPOLL  
  13.     &devpollops,  
  14. #endif   
  15. #ifdef _EVENT_HAVE_POLL  
  16.     &pollops,  
  17. #endif  
  18. #ifdef _EVENT_HAVE_SELECT  
  19.     &selectops,  
  20. #endif   
  21. #ifdef WIN32  
  22.     &win32ops,  
  23. #endif  
  24.     NULL  
  25. };  
/* Array of backends in order of preference. */
static const struct eventop *eventops[] = {
#ifdef _EVENT_HAVE_EVENT_PORTS
	&evportops,
#endif
#ifdef _EVENT_HAVE_WORKING_KQUEUE
	&kqops,
#endif
#ifdef _EVENT_HAVE_EPOLL
	&epollops,
#endif
#ifdef _EVENT_HAVE_DEVPOLL
	&devpollops,
#endif
#ifdef _EVENT_HAVE_POLL
	&pollops,
#endif
#ifdef _EVENT_HAVE_SELECT
	&selectops,
#endif
#ifdef WIN32
	&win32ops,
#endif
	NULL
};


 

了解清楚这个原理,修改一下例程,即可搞定。

int main(int argc, char** argv)
{
    /* Initalize the event library */
    struct event_config* pCfg = event_config_new();
    event_config_avoid_method(pCfg, "epoll"); // 忽略掉epoll机制
    event_config_avoid_method(pCfg, "poll");   // 忽略掉poll机制
    struct event_base* base = event_base_new_with_config(pCfg);
 
    。。。。。。
}


现在用gdb调试这个例程,在select_init函数上设置断点就可以OK了


select的几个函数都不复杂,重点分析一下select_dispatch函数

  1. static int  
  2. select_dispatch(struct event_base *base, struct timeval *tv)  
  3. {  
  4.     int res=0, i, j, nfds;  
  5.     struct selectop *sop = base->evbase;  
  6.   
  7.     check_selectop(sop);  
  8.     // 调整event_readset_out和event_writeset_out的存储空间  
  9.     if (sop->resize_out_sets) {  
  10.         fd_set *readset_out=NULL, *writeset_out=NULL;  
  11.         size_t sz = sop->event_fdsz;  
  12.         if (!(readset_out = mm_realloc(sop->event_readset_out, sz)))  
  13.             return (-1);  
  14.         sop->event_readset_out = readset_out;  
  15.         if (!(writeset_out = mm_realloc(sop->event_writeset_out, sz))) {  
  16.             /* We don't free readset_out here, since it was 
  17.              * already successfully reallocated. The next time 
  18.              * we call select_dispatch, the realloc will be a 
  19.              * no-op. */  
  20.             return (-1);  
  21.         }  
  22.         sop->event_writeset_out = writeset_out;  
  23.         sop->resize_out_sets = 0;  
  24.     }  
  25.   
  26.     memcpy(sop->event_readset_out, sop->event_readset_in,  
  27.            sop->event_fdsz);  
  28.     memcpy(sop->event_writeset_out, sop->event_writeset_in,  
  29.            sop->event_fdsz);  
  30.   
  31.     nfds = sop->event_fds+1;  
  32.   
  33.     // 在select_dispatch的上层调用函数event_base_loop中已经加锁,下面select函数并不访问event_base数据且该函数有可能阻塞,故解锁  
  34.     EVBASE_RELEASE_LOCK(base, th_base_lock);  
  35.   
  36.     res = select(nfds, sop->event_readset_out,  
  37.         sop->event_writeset_out, NULL, tv);  
  38.   
  39.     EVBASE_ACQUIRE_LOCK(base, th_base_lock);  
  40.   
  41.     check_selectop(sop);  
  42.   
  43.     if (res == -1) {  
  44.         if (errno != EINTR) {  
  45.             event_warn("select");  
  46.             return (-1);  
  47.         }  
  48.   
  49.         return (0);  
  50.     }  
  51.   
  52.     event_debug(("%s: select reports %d", __func__, res));  
  53.   
  54.     check_selectop(sop);  
  55.     // 这里比较有意思,并不是从最小的描述符开始检查,而是做了个随机处理  
  56.     i = random() % nfds;  
  57.     for (j = 0; j < nfds; ++j) {  
  58.         if (++i >= nfds)  
  59.             i = 0;  
  60.         res = 0;  
  61.         if (FD_ISSET(i, sop->event_readset_out))  
  62.             res |= EV_READ;  
  63.         if (FD_ISSET(i, sop->event_writeset_out))  
  64.             res |= EV_WRITE;  
  65.   
  66.         if (res == 0)  
  67.             continue;  
  68.                   
  69.         // 将已经ready的描述符和对应的注册事件插入event_base的事件队列中  
  70.         evmap_io_active(base, i, res);  
  71.     }  
  72.     check_selectop(sop);  
  73.   
  74.     return (0);  
  75. }  

     

     

    上一章分析了一下libevent中I/O多路复用的封装和实现,正如在select_dispatch中看到的,该函数由event_base_loo函数调用,且并不负责驱动具体事件。libevent中驱动事件的核心函数正是event_base_loop函数,该函数定义在event.c文件中。

    不过在分析event_base_loop之前,首先再详细分析一下event_base这个核心数据结构



    1. int  
    2. event_base_loop(struct event_base *base, int flags)  
    3. {  
    4.     const struct eventop *evsel = base->evsel;  
    5.     struct timeval tv;  
    6.     struct timeval *tv_p;  
    7.     int res, done, retval = 0;  
    8.   
    9.     /* Grab the lock.  We will release it inside evsel.dispatch, and again 
    10.      * as we invoke user callbacks. */  
    11.     EVBASE_ACQUIRE_LOCK(base, th_base_lock);  
    12.   
    13.     if (base->running_loop) {  
    14.         event_warnx("%s: reentrant invocation.  Only one event_base_loop"  
    15.             " can run on each event_base at once.", __func__);  
    16.         EVBASE_RELEASE_LOCK(base, th_base_lock);  
    17.         return -1;  
    18.     }  
    19.   
    20.     base->running_loop = 1;  
    21.   
    22.     // 清除base->tv_cache.tv_sec, 否则下面timeout_correct函数不会重新取系统时间  
    23.     clear_time_cache(base);  
    24.   
    25.     // 注册了信号事件,并且监视到有信号事件发生  
    26.     if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)  
    27.         evsig_set_base(base);  
    28.   
    29.     done = 0;  
    30.   
    31. #ifndef _EVENT_DISABLE_THREAD_SUPPORT  
    32.     base->th_owner_id = EVTHREAD_GET_ID();  
    33. #endif  
    34.   
    35.     base->event_gotterm = base->event_break = 0;  
    36.   
    37.     while (!done) {  
    38.         /* Terminate the loop if we have been asked to */  
    39.         if (base->event_gotterm) {  
    40.             break;  
    41.         }  
    42.   
    43.         if (base->event_break) {  
    44.             break;  
    45.         }  
    46.   
    47.         // 更新时间,调整event_base中的时间堆timeheap  
    48.         timeout_correct(base, &tv);  
    49.   
    50.         // 计算下面I/O多路复用的等待超时时间  
    51.         // 如果有激活事件,则计算到timeheap中最近的时间间隔; 否则不等待  
    52.         tv_p = &tv;  
    53.         if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {  
    54.             timeout_next(base, &tv_p);  
    55.         } else {  
    56.             /* 
    57.              * if we have active events, we just poll new events 
    58.              * without waiting. 
    59.              */  
    60.             evutil_timerclear(&tv);  
    61.         }  
    62.   
    63.         /* If we have no events, we just exit */  
    64.         if (!event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {  
    65.             event_debug(("%s: no events registered.", __func__));  
    66.             retval = 1;  
    67.             goto done;  
    68.         }  
    69.   
    70.         /* update last old time */  
    71.         gettime(base, &base->event_tv);  
    72.   
    73.         clear_time_cache(base);  
    74.   
    75.         // 调用底层I/O多路复用机制封装,如select_dispatch  
    76.         res = evsel->dispatch(base, tv_p);  
    77.   
    78.         if (res == -1) {  
    79.             event_debug(("%s: dispatch returned unsuccessfully.",  
    80.                 __func__));  
    81.             retval = -1;  
    82.             goto done;  
    83.         }  
    84.   
    85.         update_time_cache(base);  
    86.   
    87.         timeout_process(base);  
    88.   
    89.         // 处理Active事件  
    90.         if (N_ACTIVE_CALLBACKS(base)) {  
    91.             int n = event_process_active(base);  
    92.             if ((flags & EVLOOP_ONCE)  
    93.                 && N_ACTIVE_CALLBACKS(base) == 0  
    94.                 && n != 0)  
    95.                 done = 1;  
    96.         } else if (flags & EVLOOP_NONBLOCK)  
    97.             done = 1;  
    98.     }  
    99.     event_debug(("%s: asked to terminate loop.", __func__));  
    100.   
    101. done:  
    102.     clear_time_cache(base);  
    103.     base->running_loop = 0;  
    104.   
    105.     EVBASE_RELEASE_LOCK(base, th_base_lock);  
    106.   
    107.     return (retval);  
    108. }  

     

    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值