event_set(event, sfd, event_flags, base_event_handler,argvs);
//创建监听sfd句柄的可读事件,处理函数是base_event_handler,argvs是传入处理函数的参数
event_base_set(base, event);//为创建的事件event指定事件基地threads=(LIBEVENT_THREAD*)calloc(nthreads,sizeof(LIBEVENT_THREAD)); //LIBEVENT_THREAD,加入libevent元素的thread结构 “数组”
if(!threads)
{
perror("can't allocate thread des");
exit(1);
}
for(i=0;i
CQ_ITEM *item=cqi_new();
int tid=(last_thread+1)%settings.num_threads; //轮询选出workerThread(数组)
LIBEVENT_THREAD *thread=workerThreads->threads+tid;
last_thread=tid;
item->sfd=sfd; //封装必要的信息到item结构,后面会利用item封装为conn
item->init_state=init_state;
item->event_flags=event_flags;
item->read_buffer_size=read_buffer_size;
item->transport=transport;
write(thread->notify_send_fd,"c",1);//主线程和workerThread的通信方式,写入到notify_send_fd告诉辅助线程item准备好了,可以处理
last_thread++;
LIBEVENT_THREAD *me=(LIBEVENT_THREAD*)arg;
CQ_ITEM *item;
char buf[1];
if(read(fd,buf,1)!=1)
fprintf(stderr,"can't read from libevent pipe\n");
item=cq_pop(me->new_conn_queue);
if(NULL!=item)
{
conn *c= conn_new (item->sfd,item->init_state,item->event_flags,
item->read_buffer_size,item->transport,me->base);
if(NULL==c)
{
if( IS_UDP(item->transport))
{
fprintf(stderr,"can't listen for events on UDP\n");
exit(1);
}
else
{
fprintf(stderr,"can't listen for events on fd %d\n",item->sfd);
close(item->sfd);
}
}
else
{
c->thread=me;
}
cqi_free(item);
}
conn *conn_new(const int sfd,enum conn_states init_state,const int event_flags,
const int read_buffer_size,enum network_transport transport,
struct event_base *base)
{
c->sfd=sfd;
event_set(&c->event,sfd,event_flags,event_handler,(void*)c);
event_base_set(base,&c->event);
c->ev_flags=event_flags;
if(event_add(&c->event,0)==-1)
{
if( conn_add_to_freelist(c))
conn_free(c);
perror("event_add");
return NULL;
}
return c;
}