Libevent源碼分析—event_set()
阿新 • • 發佈:2017-05-30
new != void signed lag cal spa 需要 put
初始化完event_base後,下面要初始化event,通過調用event_set()實現 。相關源碼位於event.c
event_set()
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; //通過傳入的參數:fd, events, 回調函數,arg設置event的相應成員,並初始化event在小根堆中的索引為-1,以及設置event的優先級。 接下來調用event_base_set()設置event所屬的event_base。 其實在event_set()中已經將event所屬的event_base設置為當前的current_base,而current_base在event_init()中被賦值為新建的event_base。所以,如果要將一個新的event捆綁的event_base設置為新建的event_base,則可以不需要event_base_set()這步調用。如果有多個event_base,則才需要這步;就一個event_base時,是不需要這步的,因為此時current_base就等於event_base。設置event屬於當前base;current_base通過event_init()設置 ev->ev_callback = callback; //設置回調函數 ev->ev_arg = arg; //設置回調函數的3個參數 ev->ev_fd = fd; ev->ev_events = events; ev->ev_res = 0; ev->ev_flags = EVLIST_INIT; //設置event狀態 ev->ev_ncalls = 0; ev->ev_pncalls = NULL; min_heap_elem_init(ev);//初始化event在小根堆中索引為-1 min_heap.h /* by default, we put new events into the middle priority */ if(current_base) ev->ev_pri = current_base->nactivequeues/2; //設置event優先級 }
event_base_set()
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) //只能對新建的event設置其所屬event_base return (-1); ev->ev_base = base; //設置所屬event_base ev->ev_pri = base->nactivequeues/2; //設置優先級 return (0); }由上面代碼可看到,只能對新建的狀態為EVLIST_INIT的event設置所屬event_base event有優先級,我們還可以單獨調用下面的函數來專門設置event的優先級,但要求不能對活躍的event設置。
event_priority_set()
int event_priority_set(struct event *ev, int pri) { if (ev->ev_flags & EVLIST_ACTIVE) //不能對活躍的event設置優先級 return (-1); if (pri < 0 || pri >= ev->ev_base->nactivequeues) return (-1); ev->ev_pri = pri; //設置優先級 return (0); }
Libevent源碼分析—event_set()