[libevent源碼分析] event_set
來源:程序員人生 發(fā)布時間:2015-03-20 09:22:32 閱讀次數(shù):3268次
libevent使用event來封裝網(wǎng)絡事件回調,參數(shù)、fd。。。等1些信息,函數(shù)很簡單
void
event_set(struct event *ev, int fd, short events,
void (*callback)(int, short, void *), void *arg)
{
/* Take the current base - caller needs to set the real base later */
ev->ev_base = current_base; //設置成默許的current_base,如果
ev->ev_callback = callback; //設置事件回調callback;
ev->ev_arg = arg; //設置參數(shù)
ev->ev_fd = fd; //設置句柄
ev->ev_events = events; //設置當前的事件
/*
* EV_TIMEOUT 0x01
* EV_READ 0x02
* EV_WRITE 0x04
* EV_SIGNAL 0x08
* EV_PERSIST 0x10
*/
ev->ev_res = 0; //記錄當前激活事件的類型
ev->ev_flags = EVLIST_INIT; //設置事件標志,用于表示當前的事件處于甚么階段
/*
* EVLIST_TIMEOUT 0x01 //代表event在time堆中
* EVLIST_INSERTED 0x02 //代表event在已注冊時間鏈表中
* EVLIST_SIGNAL 0x04 //未見使用
* EVLIST_ACTIVE 0x08 //代表event在激活鏈表中
* EVLIST_INTERNAL 0x10 //內部使用標記
* EVLIST_INIT 0x80 //代表event已被初始化
*/
ev->ev_ncalls = 0; //代表callback被履行多少次
ev->ev_pncalls = NULL; //指向ev_ncallsor指向NULL
min_heap_elem_init(ev); //初始化時間堆中的索引值
/* by default, we put new events into the middle priority */
if(current_base)
ev->ev_pri = current_base->nactivequeues/2;//設置事件的權限為中間權限為默許值
}
使用libevent在多線程中,就會存在多個event_base來進行reactor事件模型, 就需要對struct event設置所歸屬的event_base
調用的函數(shù)以下:
int
event_base_set(struct event_base *base, struct event *ev)
{
/* Only innocent events may be assigned to a different base */
if (ev->ev_flags != EVLIST_INIT)//僅僅處在初始化中的事件對象才可以設置base,用于更新ev_base
return (⑴);
ev->ev_base = base;
ev->ev_pri = base->nactivequeues/2;
return (0);
}
這樣當每一個線程都存在1個event_base的時候,那末就能夠根據(jù)event所屬的線程來設置當前的event_base,
如果不設置event_base而使用默許,那末會使用current_base,current_base設置成最后1個創(chuàng)建的event_base對象
設置事件權限,這個函數(shù)1般都是剛創(chuàng)建完event_base的使用,由于它使用的是current_base
int
event_priority_init(int npriorities)
{
return event_base_priority_init(current_base, npriorities);
}
//重新設置event_base權限,1維是最高的。。。
int
event_base_priority_init(struct event_base *base, int npriorities)
{
int i;
if (base->event_count_active)
return (⑴);
if (base->nactivequeues && npriorities != base->nactivequeues) {
for (i = 0; i < base->nactivequeues; ++i) {
free(base->activequeues[i]);
}
free(base->activequeues);
}
/* Allocate our priority queues */
base->nactivequeues = npriorities;
base->activequeues = (struct event_list **)calloc(base->nactivequeues,
npriorities * sizeof(struct event_list *));
if (base->activequeues == NULL)
event_err(1, "%s: calloc", __func__);
for (i = 0; i < base->nactivequeues; ++i) {
base->activequeues[i] = malloc(sizeof(struct event_list));
if (base->activequeues[i] == NULL)
event_err(1, "%s: malloc", __func__);
TAILQ_INIT(base->activequeues[i]);
}
return (0);
}
libeven 全部源碼分析和sample都在我的 githup
生活不易,碼農辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈