深入理解libevent事件库的原理与实践技巧

Libevent库的介绍以及使用示例 Libevent是一个I/O框架库,具有如下特点:跨平台支持。统一事件源,Libevent对I/O事件,信号和定时事件提供统一的处理线程安全。Libevent使用libevent_pthreads库来提供线程安全支持。基于Reactor模式实现(即主线程负责事件的产生,其余线程负责对事件的处理) 阅读详情
AI摘要

本文深入介绍了libevent库的原理及应用,包括其架构设计、事件处理机制、网络缓冲区优化等内容,并探讨了如何利用libevent简化网络编程。

一、libevent简介

libevent是一个事件通知库;封装了reactor。
libevent API 提供了一种机制,用于在文件描述符上发生特定事件或达到超时后执行回调函数。此外,libevent还支持由于信号或常规超时而导致的回调。
libevent 旨在替换在事件驱动的网络服务器中找到的事件循环。应用程序只需要调用event_dispatch(),然后动态添加或删除事件,而无需更改事件循环。

目前,该控件支持/dev/poll, kqueue(), event ports, POSIX select(), Windows select(), poll(), and epoll()。内部事件机制完全独立于公开的事件 API,并且 libevent 的简单更新可以提供新功能,而无需重新设计应用程序。因此,Libevent 允许可移植应用程序开发,并提供操作系统上可用的最具可扩展性的事件通知机制。libevent 还可用于多线程应用程序,方法是隔离每个event_base,以便只有单个线程访问它,或者锁定对单个共享event_base的访问。自由的在 Linux、*BSD、Mac OS X、Solaris、Windows 等设备上编译。

libevent 还为缓冲网络 IO 提供了一个复杂的框架,支持套接字、筛选器、速率限制、SSL、零副本文件传输和 IOCP。自由度包括对几种有用协议的支持,包括 DNS、HTTP 和最小的 RPC 框架。
在这里插入图片描述

1.1、libevent编译

官网下载安装包并解压。进入解压目录执行:

./configure 
make 
sudo make install

二、reactor简介

reactor最重要的两个元素:IO和事件。既然libevent封装了reactor,那么需要了解reactor中IO、事件以及它们之间的关系。

2.1、IO

IO处理是同步的;不管是阻塞模式还是非阻塞模式,都是同步操作。reactor中IO分为:
(1)IO检测:通过IO多路复用来检测,检测IO是否就绪。
(2)IO操作:从网络协议栈中读取数据、用户层将数据写入网络协议栈中、接收连接、发起建立连接等。

2.2、事件

事件处理是异步的;reactor中处理事件是先注册事件,然后有一个事件循环,在事件循环中检测事件是否就绪,如果事件就绪了才会处理事件。注册事件和事件循环是在两个不同的流程中进行的。
reactor网络编程的主体思想是将对IO的处理转换为对事件的处理。事件分为:
(1)读事件
(2)写事件
(3)异常事件

2.3、IO与事件的关系

先注册事件,事件就绪时操作IO。 IO与事件的关系主要体现在 (1)检测IO是否就绪(通过IO多路复用)是在事件循环中进行的;(2)事件触发之后开始处理事件,处理事件过程中涉及到IO操作。

reactor做购票系统的高并发:

购票系统
线程池线程
购票请求
购票请求
购票请求
购票请求
yes
查询
返回结果
更新数据
业务处理
reactor
起始站、时间、持票人等信息
协议解析
购买成功,票数减一
是否有票
用户1
用户2
用户3
用户...
Database

三、libevent使用层次

判断点:IO是不是由程序员自己处理。
(1)在事件处理中自己处理IO。基于libevent对事件的处理。
(2)libevent内部处理IO。只需要业务逻辑的处理,由libevent处理IO操作。
(3)需要熟悉事件处理流程。

写成功
写失败
网络编程
连接的建立
接收连接
读事件
主动连接
写事件
连接的断开
主动断开
调用close()
被动断开
epollhup
读写端都关闭
write==-1 && errno == EPIPE
写端关闭
epollrdhup
读端关闭
read==0
读端关闭
数据到达
读事件
数据发送
send/write
写事件
不用注册写事件
即返回-1,注册写事件,把之前没有发生出去的数据再次发送

四、libevent封装层次

4.1、reactor 对象

主要包含:
(1)IO多路复用的对象。
(2)信号的集合;关注哪些信号的处理。
(3)触发的队列。
(4)延时处理的队列
(5)网络事件。
(6)信号事件。
(7)时间事件。

/** 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;
};

struct event_base {
	/** Function pointers and other data to describe this event_base's
	 * backend. */
	const struct eventop *evsel;
	/** Pointer to backend-specific data. */
	void *evbase;

	/** List of changes to tell backend about at next dispatch.  Only used
	 * by the O(1) backends. */
	struct event_changelist changelist;

	/** Function pointers used to describe the backend that this event_base
	 * uses for signals */
	const struct eventop *evsigsel;
	/** Data to implement the common signal handler code. */
	struct evsig_info sig;

	/** Number of virtual events */
	int virtual_event_count;
	/** Maximum number of virtual events active */
	int virtual_event_count_max;
	/** Number of total events added to this event_base */
	int event_count;
	/** Maximum number of total events added to this event_base */
	int event_count_max;
	/** Number of total events active in this event_base */
	int event_count_active;
	/** Maximum number of total events active in this event_base */
	int event_count_active_max;

	/** Set if we should terminate the loop once we're done processing
	 * events. */
	int event_gotterm;
	/** Set if we should terminate the loop immediately */
	int event_break;
	/** Set if we should start a new instance of the loop immediately. */
	int event_continue;

	/** The currently running priority of events */
	int event_running_priority;

	/** Set if we're running the event_base_loop function, to prevent
	 * reentrant invocation. */
	int running_loop;

	/** Set to the number of deferred_cbs we've made 'active' in the
	 * loop.  This is a hack to prevent starvation; it would be smarter
	 * to just use event_config_set_max_dispatch_interval's max_callbacks
	 * feature */
	int n_deferreds_queued;

	/* Active event management. */
	/** An array of nactivequeues queues for active event_callbacks (ones
	 * that have triggered, and whose callbacks need to be called).  Low
	 * priority numbers are more important, and stall higher ones.
	 */
	struct evcallback_list *activequeues;
	/** The length of the activequeues array */
	int nactivequeues;
	/** A list of event_callbacks that should become active the next time
	 * we process events, but not this time. */
	struct evcallback_list active_later_queue;

	/* common timeout logic */

	/** An array of common_timeout_list* for all of the common timeout
	 * values we know. */
	struct common_timeout_list **common_timeout_queues;
	/** The number of entries used in common_timeout_queues */
	int n_common_timeouts;
	/** The total size of common_timeout_queues. */
	int n_common_timeouts_allocated;

	/** Mapping from file descriptors to enabled (added) events */
	struct event_io_map io;

	/** Mapping from signal numbers to enabled (added) events. */
	struct event_signal_map sigmap;

	/** Priority queue of events with timeouts. */
	struct min_heap timeheap;

	/** Stored timeval: used to avoid calling gettimeofday/clock_gettime
	 * too often. */
	struct timeval tv_cache;

	struct evutil_monotonic_timer monotonic_timer;

	/** Difference between internal time (maybe from clock_gettime) and
	 * gettimeofday. */
	struct timeval tv_clock_diff;
	/** Second in which we last updated tv_clock_diff, in monotonic time. */
	time_t last_updated_clock_diff;

#ifndef EVENT__DISABLE_THREAD_SUPPORT
	/* threading support */
	/** The thread currently running the event_loop for this base */
	unsigned long th_owner_id;
	/** A lock to prevent conflicting accesses to this event_base */
	void *th_base_lock;
	/** A condition that gets signalled when we're done processing an
	 * event with waiters on it. */
	void *current_event_cond;
	/** Number of threads blocking on current_event_cond. */
	int current_event_waiters;
#endif
	/** The event whose callback is executing right now */
	struct event_callback *current_event;

#ifdef _WIN32
	/** IOCP support structure, if IOCP is enabled. */
	struct event_iocp_port *iocp;
#endif

	/** Flags that this base was configured with */
	enum event_base_config_flag flags;

	struct timeval max_dispatch_time;
	int max_dispatch_callbacks;
	int limit_callbacks_after_prio;

	/* Notify main thread to wake up break, etc. */
	/** True if the base already has a pending notify, and we don't need
	 * to add any more. */
	int is_notify_pending;
	/** A socketpair used by some th_notify functions to wake up the main
	 * thread. */
	evutil_socket_t th_notify_fd[2];
	/** An event used by some th_notify functions to wake up the main
	 * thread. */
	struct event th_notify;
	/** A function used to wake up the main thread from another thread. */
	int (*th_notify_fn)(struct event_base *base);

	/** Saved seed for weak random number generator. Some backends use
	 * this to produce fairness among sockets. Protected by th_base_lock. */
	struct evutil_weakrand_state weakrand_seed;

	/** List of event_onces that have not yet fired. */
	LIST_HEAD(once_event_list, event_once) once_events;

};
变量含义
evsel和evbase选择的哪种IO多路复用;struct eventop是具体的接口。
changelist事件数组,比如epoll中的struct epoll_event或者select中的fd_set。
evsigsel和sig信号处理。libevent对事件做了高度抽象,不仅仅是网络事件还有信号事件、定时事件,这些事件全部封装为事件对象。
activequeues被触发的队列。比如epoll_wait返回的就绪事件全部放入activequeues中。
nactivequeuesactivequeues的长度。
active_later_queue延时处理队列。需要延时处理的事件放入这个队列中。
io具体的网络事件IO的map。
sigmap信号事件IO的map。
timeheap时间时间的最小堆。

reactor对象封装为struct event_base;通过:
(1)event_base_new()构造对象。
(2)event_base_free()销毁对象。

4.2、事件对象

事件对象通过struct event的结构体封装使用。

struct event {
	struct event_callback ev_evcallback;

	/* for managing timeouts */
	union {
		TAILQ_ENTRY(event) ev_next_with_common_timeout;
		int min_heap_idx;
	} ev_timeout_pos;
	evutil_socket_t ev_fd;

	struct event_base *ev_base;

	union {
		/* used for io events */
		struct {
			LIST_ENTRY (event) ev_io_next;
			struct timeval ev_timeout;
		} ev_io;

		/* used by signal events */
		struct {
			LIST_ENTRY (event) ev_signal_next;
			short ev_ncalls;
			/* Allows deletes in callback */
			short *ev_pncalls;
		} ev_signal;
	} ev_;

	short ev_events;
	short ev_res;		/* result passed to event callback */
	struct timeval ev_timeout;
};
变量含义
ev_evcallback回调函数。事件是异步处理的,需要回调函数。
min_heap_idx时间事件的最小堆的索引。
ev_fd定时事件的fd。
ev_base事件对象所属的reactor的对象。
ev_io网络事件关注的事情。
ev_signal信号事件关注的事情。
ev_timeout超时。
ev_timeout_pos和ev_fd定时任务处理的事情。
ev_events具体注册的事件。
ev_具体的信号。

通常,event对象可以自己处理IO。
(1)event_new():构建事件对象、绑定、事件回调。
(2)event_free():销毁事件对象。

bufferevent和evconnlistener对象只需要关注业务逻辑的处理,由libevent内部处理IO操作。

bufferevent是在event对象上面封装的缓冲区。

/**
   Implementation table for a bufferevent: holds function pointers and other
   information to make the various bufferevent types work.
*/
struct bufferevent_ops {
	/** The name of the bufferevent's type. */
	const char *type;
	/** At what offset into the implementation type will we find a
	    bufferevent structure?

	    Example: if the type is implemented as
	    struct bufferevent_x {
	       int extra_data;
	       struct bufferevent bev;
	    }
	    then mem_offset should be offsetof(struct bufferevent_x, bev)
	*/
	off_t mem_offset;

	/** Enables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
	    not need to adjust the 'enabled' field.  Returns 0 on success, -1
	    on failure.
	 */
	int (*enable)(struct bufferevent *, short);

	/** Disables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
	    not need to adjust the 'enabled' field.  Returns 0 on success, -1
	    on failure.
	 */
	int (*disable)(struct bufferevent *, short);

	/** Detatches the bufferevent from related data structures. Called as
	 * soon as its reference count reaches 0. */
	void (*unlink)(struct bufferevent *);

	/** Free any storage and deallocate any extra data or structures used
	    in this implementation. Called when the bufferevent is
	    finalized.
	 */
	void (*destruct)(struct bufferevent *);

	/** Called when the timeouts on the bufferevent have changed.*/
	int (*adj_timeouts)(struct bufferevent *);

	/** Called to flush data. */
	int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode);

	/** Called to access miscellaneous fields. */
	int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);

};

/**
  Shared implementation of a bufferevent.

  This type is exposed only because it was exposed in previous versions,
  and some people's code may rely on manipulating it.  Otherwise, you
  should really not rely on the layout, size, or contents of this structure:
  it is fairly volatile, and WILL change in future versions of the code.
**/
struct bufferevent {
	/** Event base for which this bufferevent was created. */
	struct event_base *ev_base;
	/** Pointer to a table of function pointers to set up how this
	    bufferevent behaves. */
	const struct bufferevent_ops *be_ops;

	/** A read event that triggers when a timeout has happened or a socket
	    is ready to read data.  Only used by some subtypes of
	    bufferevent. */
	struct event ev_read;
	/** A write event that triggers when a timeout has happened or a socket
	    is ready to write data.  Only used by some subtypes of
	    bufferevent. */
	struct event ev_write;

	/** An input buffer. Only the bufferevent is allowed to add data to
	    this buffer, though the user is allowed to drain it. */
	struct evbuffer *input;

	/** An input buffer. Only the bufferevent is allowed to drain data
	    from this buffer, though the user is allowed to add it. */
	struct evbuffer *output;

	struct event_watermark wm_read;
	struct event_watermark wm_write;

	bufferevent_data_cb readcb;
	bufferevent_data_cb writecb;
	/* This should be called 'eventcb', but renaming it would break
	 * backward compatibility */
	bufferevent_event_cb errorcb;
	void *cbarg;

	struct timeval timeout_read;
	struct timeval timeout_write;

	/** Events that are currently enabled: currently EV_READ and EV_WRITE
	    are supported. */
	short enabled;
};

struct bufferevent中的重要成员变量:

变量含义
ev_base事件对象所属的reactor的对象。
be_opsbufferevent的具体操作。控制某个事件的打开、关闭、移除等,其中input是用户态读缓冲区,output是用户态写缓冲区
readcb读事件的回调函数
writecb注意不是写事件回调,而是低水平触发的回调函数。这是涉及到写失败时的处理,内部会处理写事件发送出去。通常不需要设置写回调函数。
errorcb所有错误事件的回调函数。被动关闭连接或其他异常的回调函数。
wm_read读水平线,里面分有高水平和低水平。低水平是指buffer中有多少数据就要触发回调,默认为0,即每次读事件都会触发回调;高水平是指缓冲区中达到多大的数据就要关闭读事件,即buffer数据比较多的时候不再处理读事件。
wm_write写水平线,写只有低水平没有高水平。低水平默认值是0,即用户态缓冲区为空时回调写回调函数。

struct bufferevent_ops中的重要成员变量:

变量含义
input用户态读缓冲区。
output用户态写缓冲区。

(1)bufferevent_socket_new():构建bufferevent对象。
(2)bufferevent_free():销毁bufferevent对象。

evconnlistener是专门处理listenfd的对象,使我们不需要关注bind、listen、accept的具体操作。

struct evconnlistener_ops {
	int (*enable)(struct evconnlistener *);
	int (*disable)(struct evconnlistener *);
	void (*destroy)(struct evconnlistener *);
	void (*shutdown)(struct evconnlistener *);
	evutil_socket_t (*getfd)(struct evconnlistener *);
	struct event_base *(*getbase)(struct evconnlistener *);
};

struct evconnlistener {
	const struct evconnlistener_ops *ops;
	void *lock;
	evconnlistener_cb cb;
	evconnlistener_errorcb errorcb;
	void *user_data;
	unsigned flags;
	short refcnt;
	int accept4_flags;
	unsigned enabled : 1;
};

(1)evconnlistener_new():构建evconnlistener对象、绑定、事件回调。
(2)evconnlistener_free():销毁evconnlistener对象。
(3)evconnlistener_bind_new():创建listenfd、bind、listen、注册读事件。

4.3、事件操作

event对象:
(1)event_add(),注册事件。
(2)event_del(),注销事件。
bufferevent对象:
(1)bufferevent_enable(),注册事件。
(2)bufferevent_disable(),注销事件。

4.4、事件循环

int event_base_dispatch(struct event_base *event_base)
{
	return (event_base_loop(event_base, 0));
}

int
event_base_loop(struct event_base *base, int flags)
{
	const struct eventop *evsel = base->evsel;//事件操作相关的接口
	struct timeval tv;
	struct timeval *tv_p;
	int res, done, retval = 0;

	/* Grab the lock.  We will release it inside evsel.dispatch, and again
	 * as we invoke user callbacks. */
	EVBASE_ACQUIRE_LOCK(base, th_base_lock);

	if (base->running_loop) {
		event_warnx("%s: reentrant invocation.  Only one event_base_loop"
		    " can run on each event_base at once.", __func__);
		EVBASE_RELEASE_LOCK(base, th_base_lock);
		return -1;
	}

	base->running_loop = 1;

	clear_time_cache(base);

	if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)
		evsig_set_base_(base);

	done = 0;

#ifndef EVENT__DISABLE_THREAD_SUPPORT
	base->th_owner_id = EVTHREAD_GET_ID();
#endif

	base->event_gotterm = base->event_break = 0;

	while (!done) {
		base->event_continue = 0;
		base->n_deferreds_queued = 0;

		/* Terminate the loop if we have been asked to */
		if (base->event_gotterm) {
			break;
		}

		if (base->event_break) {
			break;
		}
		// 定时任务
		tv_p = &tv;
		if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {
			timeout_next(base, &tv_p);
		} else {
			/*
			 * if we have active events, we just poll new events
			 * without waiting.
			 */
			evutil_timerclear(&tv);
		}

		/* If we have no events, we just exit */
		if (0==(flags&EVLOOP_NO_EXIT_ON_EMPTY) &&
		    !event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
			event_debug(("%s: no events registered.", __func__));
			retval = 1;
			goto done;
		}

		event_queue_make_later_events_active(base);

		clear_time_cache(base);

		res = evsel->dispatch(base, tv_p);

		if (res == -1) {
			event_debug(("%s: dispatch returned unsuccessfully.",
				__func__));
			retval = -1;
			goto done;
		}

		update_time_cache(base);

		timeout_process(base);//收集定时任务

		if (N_ACTIVE_CALLBACKS(base)) {
			int n = event_process_active(base);//处理队列事件
			if ((flags & EVLOOP_ONCE)
			    && N_ACTIVE_CALLBACKS(base) == 0
			    && n != 0)
				done = 1;
		} else if (flags & EVLOOP_NONBLOCK)
			done = 1;
	}
	event_debug(("%s: asked to terminate loop.", __func__));

done:
	clear_time_cache(base);
	base->running_loop = 0;

	EVBASE_RELEASE_LOCK(base, th_base_lock);

	return (retval);
}

(1)事件循环:event_base_dispatch(),event_base_loop()。
(2)事件循环退出:event_base_loopexit(),event_base_break()。

int
event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
{
	return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
		    event_base, tv));
}

/* Schedules an event once */
int
event_base_once(struct event_base *base, evutil_socket_t fd, short events,
    void (*callback)(evutil_socket_t, short, void *),
    void *arg, const struct timeval *tv)
{
	struct event_once *eonce;
	int res = 0;
	int activate = 0;

	if (!base)
		return (-1);

	/* We cannot support signals that just fire once, or persistent
	 * events. */
	if (events & (EV_SIGNAL|EV_PERSIST))
		return (-1);

	if ((eonce = mm_calloc(1, sizeof(struct event_once))) == NULL)
		return (-1);

	eonce->cb = callback;
	eonce->arg = arg;

	if ((events & (EV_TIMEOUT|EV_SIGNAL|EV_READ|EV_WRITE|EV_CLOSED)) == EV_TIMEOUT) {
		evtimer_assign(&eonce->ev, base, event_once_cb, eonce);

		if (tv == NULL || ! evutil_timerisset(tv)) {
			/* If the event is going to become active immediately,
			 * don't put it on the timeout queue.  This is one
			 * idiom for scheduling a callback, so let's make
			 * it fast (and order-preserving). */
			activate = 1;
		}
	} else if (events & (EV_READ|EV_WRITE|EV_CLOSED)) {
		events &= EV_READ|EV_WRITE|EV_CLOSED;

		event_assign(&eonce->ev, base, fd, events, event_once_cb, eonce);
	} else {
		/* Bad event combination */
		mm_free(eonce);
		return (-1);
	}

	if (res == 0) {
		EVBASE_ACQUIRE_LOCK(base, th_base_lock);
		if (activate)
			event_active_nolock_(&eonce->ev, EV_TIMEOUT, 1);
		else
			res = event_add_nolock_(&eonce->ev, tv, 0);

		if (res != 0) {
			mm_free(eonce);
			return (res);
		} else {
			LIST_INSERT_HEAD(&base->once_events, eonce, next_once);
		}
		EVBASE_RELEASE_LOCK(base, th_base_lock);
	}

	return (0);
}

4.5、事件处理

设置事件相对应的回调。
(1)如果是使用event对象,在event_new()会设置相对应的回调。
(2)如果IO由libevent处理,那么使用bufferevent_setcb()来设置回调。

void
bufferevent_setcb(struct bufferevent *bufev,
    bufferevent_data_cb readcb, bufferevent_data_cb writecb,
    bufferevent_event_cb eventcb, void *cbarg)
{
	BEV_LOCK(bufev);

	bufev->readcb = readcb;
	bufev->writecb = writecb;
	bufev->errorcb = eventcb;

	bufev->cbarg = cbarg;
	BEV_UNLOCK(bufev);
}

五、libevent解决了网络编程哪些痛点?

5.1、高效的网络缓冲区

在内核中有读缓冲区和写缓冲区,减少用户态和内核态的切换。
用户态读缓冲区的存在是为了处理粘包的问题,因为网络协议栈是不知道用户界定数据包的格式,没法确定一个完整的数据包。
用户态写缓冲区的存在是因为用户根本不清楚内核写缓存区的状态,需要把没有写出去的数据缓存起来等待下次写事件时把数据写出去。
buffer的设计有三种类型:
(1)固定数组,固定长度。限定了处理数据包的能力,没有动态伸缩的能力;需要频繁挪动数据。
(2)ring buffer。可伸缩性差。
(3)chain buffer。解决可伸缩性差的问题,避免频繁挪动数据;同时也引进了新的问题,一个数据可能在多个buffer中都有,即数据分割,这会导致多次系统调用,从而引起中断上下文的切换。解决办法是使用readv()将内核中连续的buffer读到用户态不连续的buffer中,writev()把用户态不连续的buffer写到内核连续的buffer中;从而减少系统调用。
libevent

evbuffer就是chain buffer类型的缓冲区。

5.2、IO函数使用与网络原理

(1)有了libevent可以不使用IO函数。因为如果使用IO函数,既需要知道这些IO函数里面的系统调用返回值的含义。
(2)有了libevent就可以不清楚数据拷贝原理。
(3)有了libevent就可以不清楚网络原理以及网络编程流程。
(4)有了libevent只需要知道事件处理,IO操作完全交由libevent处理。

5.3、多线程

加锁的效果比较好。
一个线程尽量只处理一个reactor的事件。
(1)buffer加锁时,读要读出一个完整的数据包。
(2)buffer加锁时,写要写一个完整的数据包。

总结

  1. libevent是一个事件通知库,目标是对事件编程;它封装了reactor。

  2. reactor需要关注的几个点:IO分为IO检测(IO多路复用检测IO是否就绪)、IO操作;必须明白IO处理是同步到,而事件处理是异步的(注册事件和事件就绪时触发事件回调是不在同一个流程进行的)。

  3. libevent使用层次有:在事件中自己处理IO和只需要处理业务逻辑(libevent内部处理IO)两种方式。

  4. libevent的封装层次:通常,把事件对象绑定到reactor对象上面;需要熟悉事件操作、事件处理、事件循环。

  5. libevent解决了网络编程中IO函数处理的痛点,因为多线程环境下很难处理IO函数的返回值,以及很难控制数据安全性。

  6. libevent具有高效的网络缓冲区,evbuffer采用chain buffer类型的缓冲区,伸缩性好而且不需要频繁挪动数据。

在这里插入图片描述

libevent核心原理 Libevent 是一个轻量级的高性能网络库,事件驱动,基于 Reactor 模式。 对 Libevent 源码的阅读可围绕事件管理展开: Libevent 对三类事件源进行了统一,用 event 结构体表示,每个 event 实例表示一个事件。 同时监听多个事件(比如监听多个 socket 上的可读事件),必然会有多个 event 实例,对这些 event 实例进行管理需要特定的数据结构,Li... 阅读详情

相关推荐

libevent 源码分析丨libevent组件构成以及编程要领

1,前言 Libevent是一个轻量级的开源高性能网络库,使用者众多,研究者更甚,相关文章也不少。写这一系列文章的用意在于,一则分享心得;二则对libevent代码和设计思想做系统的、更深层次的分析,写出来,也可供后来者参考。文章较长,建议收藏观看。 附带一句:Libevent是用c语言编写的(MS大牛们都偏爱c语言哪),而且几乎是无处不函数指针,学习其源代码也需要相当的c语言基础。 文章相关视频讲解: c/c++Linux后台服务器开发高级架构师视频资料 epoll原理剖析以及reactor模型

Linuxhus的博客 423

Libevent学习

1)事件2)事件集合3)关联的文件描述符4)事件类型5)回调函数6)回调函数的参数1)basestruct event_base类型的指针,表示事件集合2)cbevconnlistener_cb类型的回调函数指针,用于处理新连接的事件。其中:evconnlistener_cb类型3)ptr传递给回调函数的参数指针4)flags标志位,可以是或等选项其中:5)backlog:监听队列的长度。

qq_50615776的博客 4191

libevent解读一

一、接触libevent libevent是用C语言编写的开源高性能网络库,是学习网络编程、后台开发必备的源码学习资料。其源代码相当精炼、易读,设计技巧和技术框架也很精彩,所以在此我也将我的理解与思考与大家分享,后期我自己也模仿实现了C++版本的网络库,欢迎一起来讨论。 二、libevent特点 高性能,体现在使用了事件驱动的设计模式,即Reactor模型。 跨平台,支持目前几乎所

handaifeng的专栏 440

Libevent库的介绍与应用

Libevent库Libevent概述Libevent使用模型Libevent库使用示例Libevent事件类型和框架结构 Libevent概述 Libevent是开源社区的一款高性能的I/O框架库,使用Libevent的著名案例有:高性能的分布式内存对象缓存软件memcached,Googlo浏览器Chromium的Linux版本。作为一个I/O框架库

XXXTENTAC1ON的博客 5235

深入理解Memcached原理

1.为什么要使用memcache  由于网站的高并发读写需求,传统的关系型数据库开始出现瓶颈,例如: 1)对数据库的高并发读写: 关系型数据库本身就是个庞然大物,处理过程非常耗时(如解析SQL语句,事务处理等)。如果对关系型数据库进行高并发读写(每秒上万次的访问),那么它是无法承受的。 2)对海量数据的处理: 对于大型的SNS网站,每天有上千万次的数据产生(如twitter, 新浪微博)

Java我人生的技术博客 1万+

开源事件通知库libevent及网络连接管理模块bufferevent详解

开源事件通知库libevent及网络连接管理模块bufferevent详解

dvlinker的技术专栏 1万+

libevent(1)之基础概述

libevent是一个功能强大的跨平台事件驱动库,在高性能网络编程领域有着广泛的应用。它最初由Niels Provos等人开发,最早可以追溯到2000年。经过多年的发展演进,目前已经成为了业内公认的优秀开源项目之一。 作为一个专注于事件驱动和异步I/O的编程库,libevent帮助开发者以一种高效而统一的方式处理各种类型的事件,比如网络I/O、定时器、信号等。它能够自动利用操作系统提供的最佳I/O多路复用机制,如Linux上的epoll、BSD上的kqueue等,从而实现了可移植性和高性能。

梅花香自苦寒来,宝剑锋从磨砺出。 1745

libevent2事件通知库:手册与核心技术解析

Libevent2是一个跨平台的事件处理库,其主要设计目的是简化网络编程的复杂性,提供一种快速、可扩展的方式来处理多种类型的事件,如文件描述符的可读/可写、定时器、信号等。该库支持多种操作系统,包括Unix、Linux以及Windows。它特别适用于需要同时处理多个网络连接和各种事件的高并发服务器应用。在本章节中,我们将对libevent2库的基本概念、特点及其在现代网络编程中的重要性进行浅入深出的探讨。通过本章学习,读者将对libevent2有一个全面的了解,并为深入学习后续章节打下坚实基础。

weixin_42602726的博客 1071

Libevent(3)之使用教程(2)创建事件

本文介绍了Libevent库中event_base的创建和配置方法。主要内容包括:使用event_base_new()创建默认event_base;通过event_config结构体进行更精确的配置,包括禁用特定后端方法、设置功能要求和运行时标志;以及多CPU环境下的优化提示。文章详细说明了各种配置选项的含义和使用场景,并指出配置不满足时可能返回NULL的情况。这些内容为使用Libevent进行高效网络编程提供了基础支持。

梅花香自苦寒来,宝剑锋从磨砺出。 2059

libevent 2.1.11实战:从事件循环原理到高并发网络编程

在C/C++网络开发中,I/O多路复用技术是构建高并发服务的核心基础。传统多线程模型在线程切换和内存开销上存在瓶颈,而事件驱动机制通过单线程事件循环管理非阻塞I/O,由内核高效通知文件描述符就绪状态,显著降低系统负载。libevent正是这样一个跨平台事件通知库,它统一封装了epoll、kqueue等底层backend,为上层提供简洁的注册、回调与分发API。本文以libevent-2.1.11-stable版本为主线,介绍其编译安装、event_base与bufferevent核心编程模型,并结合TCP

weixin_42525369的博客 255

【R语言】富集分析可视化代码(整理版)

分别介绍了如何使用DAVID在线分析工具对基因进行GO/KEGG功能富集分析、使用R ggplot包对获得的基因GO/KEGG功能富集结果进行可视化、使用R clusterProfiler包和R AnnotationHub包对基因进行GO/KEGG功能富集分析、OrgDb包制作以及结果可视化等。故,我重新整理了一波,并补充了可对多个分组的富集结果进行可视化以及富集结果绘制圈图等的代码。关注“在打豆豆的小潘学长”公众号,发送“富集分析3”获得完整代码包和演示数据。一、单组富集结果可视化。

weixin_54004950的博客 1万+

libevent参考手册中文版:助力开发者深入理解与实践

libevent参考手册中文版:助力开发者深入理解与实践 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在开源社区中,libevent是一个被广泛使用的跨平台事件驱动编程库,它能够帮助开发者处理不同类型的输入事件。libevent参考手册中文版项目,为开发者提供了libevent-2.1.5的中文参考手册,采用PDF格式,详细介绍了libevent库的设计理念、工作原...

gitblog_06780的博客 585

手教你如何使用Simulink和相关工具箱模拟和实现无人机的多机接力信号中继的建模

扩大通信范围:单架无人机的通信能力有限,通过多机接力的方式可以显著扩展通信覆盖范围。提高可靠性:当某架无人机出现故障或电量不足时,其他无人机可以接管其任务,确保通信不中断。适应复杂环境:在山区、森林等复杂地形中,多机接力可以绕过障碍物,建立稳定的通信链路。使用Communications Toolbox中的模块来模拟无线通信链路。例如,可以使用模块模拟噪声信道,或者使用模块计算信号衰减。matlab深色版本。

MHD0815的博客 769

深入解析libevent事件驱动机制与性能优化

事件驱动架构是现代高并发系统的核心技术之一,其核心原理是通过事件循环机制高效处理I/O事件。libevent作为经典的事件驱动库,采用多路复用技术(如epoll、kqueue)实现高性能事件监听,通过事件注册、分发和回调机制构建异步编程模型。在性能优化方面,libevent运用时间缓存、内存池化等技术显著提升吞吐量,特别适合需要处理大量并发连接的网络服务。结合线程模型和缓冲区管理,开发者可以构建出稳定高效的网络应用。本文以libevent为例,详细剖析事件驱动库的核心实现机制与工程实践要点。

weixin_30770783的博客 398

深入解析AMBA5 AXI与ACE协议:从基础到高级应用

本文深入解析了AMBA5 AXI与ACE协议的核心机制与应用。AXI协议通过分离通道、突发传输和乱序完成实现高性能数据传输,而ACE协议在此基础上构建了硬件级缓存一致性解决方案,通过监听机制和状态模型确保多核系统数据统一。文章还探讨了在异构计算等复杂场景下的实战应用与AMBA5的新特性。

cc789的博客 964

STM32CubeMX Nucleo F767ZI 教程(1)

系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 例如:第一章 Python 机器学习入门之pandas的使用 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录系列文章目录前言一、pandas是什么?二、使用步骤1.引入库2.读入数据总结 前言 官网上买了个NUCLEO F767ZI 的开发板,144引脚的芯片,https://www.st.com/content/st_com/zh/products/evaluation-tools/prod

fafuwxm 2035

chromium libevent

chromium android/linux/mac 中用libevent来做为底层io检测

finding的专栏 2218

时间序列聚类在股票市场分析中的实践与优化

时间序列聚类是一种面向动态行为建模的无监督学习方法,其核心在于通过语义感知的距离度量(如DTW)捕捉价格形态的相位弹性与结构相似性,而非依赖静态数值或标签驱动。相比K-Means等传统算法,它能有效缓解金融时序中普遍存在的噪声敏感、对齐失效与形态失真问题,从而提升聚类结果的市场可解释性与策略鲁棒性。该技术已广泛应用于市场状态识别、行业行为分群、异常交易监测等场景,并成为构建可验证量化分析框架的关键预处理层。本文聚焦A股真实行情数据,详解从原始OHLCV到可聚类时间序列的完整链路,涵盖DTW距离计算、层次聚类

weixin_34220179的博客 832

深入理解libevent:C语言高性能网络编程的事件驱动框架

在C语言网络编程中,I/O多路复用技术是构建高并发服务器的核心基础。通过select、poll或epoll等系统调用,程序可以同时监控多个文件描述符的状态,实现单线程处理大量连接,这是高性能网络服务的关键原理。这种事件驱动模型极大地提升了资源利用率和程序吞吐量,其技术价值在于能够以较低的系统开销支撑海量并发连接,广泛应用于游戏服务器、实时通信和消息推送等高负载场景。libevent正是封装了底层不同操作系统的I/O多路复用机制,提供了统一、高效的事件通知库,让开发者从复杂的手动事件管理中解放出来。本文聚焦于

weixin_33794672的博客 427

Axure RP 9在Windows 11环境下的高效安装与配置指南

本文提供Axure RP 9在Windows 11系统下的详细安装步骤与配置指南。针对Win11安全特性,从获取官方安装资源、调整系统权限,到定制化安装路径、精准汉化及性能优化,系统性地解决了安装闪退、汉化失败、运行卡顿等常见问题,确保用户获得稳定流畅的原型设计体验。

mango的博客 481

Qt | linux+openCV+Qt6.5.3环境搭建成功版(带例子)

opencv安装 Qt 实战举例

Qt历险记,专注Qt技术,三年医疗设备研发经验,1年机器视觉研发经验,半年柔性传感研发经验。 1887

零基础掌握Libevent:Nick‘s libevent manual中的10个关键示例代码详解

Libevent是一个高性能的事件驱动网络库,广泛应用于开发可扩展的网络服务器和客户端。本指南基于Nick's libevent manual项目,精选10个关键示例代码,帮助零基础开发者快速掌握Libevent的核心功能与应用场景。通过这些示例,你将学习如何利用Libevent构建高效的非阻塞IO应用,理解事件循环、缓冲事件、连接监听器等核心组件的工作原理。 ## 1. 事件驱动基础:rot1

gitblog_00773的博客 350

LPDDR5 学习笔记01:功能概述

LPDDR5/LPDDR5X SDRAM设备采用8/16DQ通道架构,支持2Gb-32Gb容量。通过CK命令时钟和更快的WCK数据时钟协同工作,7个CA引脚传输控制信息,支持2:1或4:1的WCK:CK比例。设备提供BG/8B/16B三种存储模式选择,分别支持不同数据速率(最高8.533Gbps)和突发长度。采用0.5V VDDQ电源电压,实现高速双倍数据速率传输,并通过差分WCK时钟完成数据采样。读写采用突发访问机制,需先激活命令再执行读写操作。新型LPDDR5X仅支持BG和16B模式,优化了高速性能。

一只豌豆象的博客 2206

Libevent(4)之使用教程(3)配置

本文介绍了Libevent事件库中事件配置的基本概念和使用方法。主要内容包括: 事件的生命周期:从初始化、待处理到活跃状态的转换过程,以及持久化事件的特性。 事件构造:使用event_new()函数创建事件对象,需要指定事件基础、文件描述符、触发标志、回调函数和参数。 事件标志:详细说明了EV_TIMEOUT、EV_READ、EV_WRITE等标志的作用和使用场景。 持久化事件:解释了EV_PERSIST标志如何使事件在触发后保持待处理状态,以及超时重置机制。 回调参数传递:介绍如何使用event_self

梅花香自苦寒来,宝剑锋从磨砺出。 1842

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

vs2013 调试libevent 源码

自己内功的提升,无非是向前辈学习和修炼自身,对于编码也是如此,学习优秀的库只有从 源代码学起,才能深刻理解库实现的来龙去脉,加深自己的理解,提升自己的功力。 今天就介绍一下vs2013 下面调试libevent源码。不需要创建sln解决方案,只需要创建工程,包含 源码目录即可源码调试。 1、手工添加print-winsocke-errors.c文件,不然nmake编译的时候会报...

194

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

libevent(2)之使用教程(1)介绍

Libevent 是用于开发快速可移植非阻塞 IO 程序的库,其设计目标包括:使用 Libevent 编写的程序应能在所有 Libevent 支持的平台上运行。即便在没有理想非阻塞 IO 实现的情况下,Libevent 也应支持次优方案,确保程序能在受限环境中运行。Libevent 会尝试在各平台上使用可用的最快非阻塞 IO 实现,且尽量不引入过多开销。Libevent 的设计即使在程序需要管理数万个活跃套接字时也能良好工作。

梅花香自苦寒来,宝剑锋从磨砺出。 1589

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

上一篇: 深入理解模板方法模式的设计原理与实战技巧
下一篇: Linux基础组件之libevent实践
Lion 莱恩呀
Lion 莱恩呀 CSDN实力新星 CSDN实力新星 领域专家: 数据库技术领域 领域专家: 数据库技术领域
博客等级 码龄8年 7万+粉丝 638原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lion 莱恩呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值