memcached的通信机制是有一个主线程负责监听来的请求,然后main thread负责将得到的请求分发到各个worker thread中。
每个worker thread维护一个请求队列。
主线程通过如下方式与worker 线程交互:
与线程相关的核心代码都在thread.c当中。
-
/*
-
* Dispatches a new connection to another thread. This is only ever called
-
* from the main thread, either during initialization (for UDP) or because
-
* of an incoming connection.
-
*/
-
void dispatch_conn_new(int sfd, enum conn_states init_state, int event_flags,
-
int read_buffer_size, enum network_transport transport) {
-
CQ_ITEM *item = cqi_new();
-
char buf[1];
-
int tid = (last_thread + 1) % settings.num_threads;
-
-
LIBEVENT_THREAD *thread = threads + tid;
-
-
last_thread = tid;
-
-
item->sfd = sfd;
-
item->init_state = init_state;
-
item->event_flags = event_flags;
-
item->read_buffer_size = read_buffer_size;
-
item->transport = transport;
-
-
cq_push(thread->new_conn_queue, item);
-
-
MEMCACHED_CONN_DISPATCH(sfd, thread->thread_id);
-
buf[0] = 'c';
-
if (write(thread->notify_send_fd, buf, 1) != 1) {
-
perror("Writing to thread notify pipe");
-
}
-
}
主线程通过轮询将请求发送到相应的线程中。threads是一个全局的变量,cq_push将写请求放入到该线程的队列中。向thread的管道中写入一个字节的内容,通知工作线程,处理自己的线程队列里面的任务。
阅读(3220) | 评论(0) | 转发(0) |