memcached线程模型分析

目前网上关于memcached的分析主要是内存管理部分,下面对memcached的线程模型做下简单分析 
有不对的地方还请大家指正,memcahcedlibevent不熟悉的请先google 

先看下memcahced启动时线程处理的流程 
 

memcached的多线程主要是通过实例化多个libevent实现的,分别是一个主线程和nworkers线程 
无论是主线程还是workers线程全部通过libevent管理网络事件,实际上每个线程都是一个单独的libevent实例 

主线程负责监听客户端的建立连接请求,以及accept 连接 
workers线程负责处理已经建立好的连接的读写等事件 

先看一下大致的图示: 
 

首先看下主要的数据结构(thread.c) 

C代码 

1.            /* An item in the connection queue. */  

2.            typedef struct conn_queue_item CQ_ITEM;  

3.            struct conn_queue_item {  

4.                int     sfd;  

5.                int     init_state;  

6.                int     event_flags;  

7.                int     read_buffer_size;  

8.                int     is_udp;  

9.                CQ_ITEM *next;  

10.          };  



CQ_ITEM 实际上是主线程accept后返回的已建立连接的fd的封装 

C代码 

1.            /* A connection queue. */  

2.            typedef struct conn_queue CQ;  

3.            struct conn_queue {  

4.                CQ_ITEM *head;  

5.                CQ_ITEM *tail;  

6.                pthread_mutex_t lock;  

7.                pthread_cond_t  cond;  

8.            };  



CQ是一个管理CQ_ITEM的单向链表 

C代码 

1.            typedef struct {  

2.                pthread_t thread_id;        /* unique ID of this thread */  

3.                struct event_base *base;    /* libevent handle this thread uses */  

4.                struct event notify_event;  /* listen event for notify pipe */  

5.                int notify_receive_fd;      /* receiving end of notify pipe */  

6.                int notify_send_fd;         /* sending end of notify pipe */  

7.                CQ  new_conn_queue;         /* queue of new connections to handle */  

8.            } LIBEVENT_THREAD;  



这是memcached里的线程结构的封装,可以看到每个线程都包含一个CQ队列,一条通知管道pipe 
和一个libevent的实例event_base 

另外一个重要的最重要的结构是对每个网络连接的封装conn 

C代码 

1.            typedef struct{  

2.              int sfd;  

3.              int state;  

4.              struct event event;  

5.              short which;  

6.              char *rbuf;  

7.              ... //这里省去了很多状态标志和读写buf信息等  

8.            }conn;  


memcached主要通过设置/转换连接的不同状态,来处理事件(核心函数是drive_machine 

下面看下线程的初始化流程: 

memcached.cmain函数中,首先对主线程的libevent做了初始化 

C代码 

1.            /* initialize main thread libevent instance */  

2.             main_base = event_init();  



然后初始化所有的workers线程,并启动,启动过程细节在后面会有描述 

C代码 

1.            /* start up worker threads if MT mode */  

2.            thread_init(settings.num_threads, main_base);  


接着主线程调用(这里只分析tcp的情况,目前memcached支持udp方式) 

C代码 

1.            server_socket(settings.port, 0)  


这个方法主要是封装了创建监听socket,绑定地址,设置非阻塞模式并注册监听socket 
libevent 读事件等一系列操作 

然后主线程调用 

C代码 

1.            /* enter the event loop */  

2.            event_base_loop(main_base, 0);  



这时主线程启动开始通过libevent来接受外部连接请求,整个启动过程完毕 

下面看看thread_init是怎样启动所有workers线程的,看一下thread_init里的核心代码 

C代码 

1.            void thread_init(int nthreads, struct event_base *main_base) {  

2.             //。。。省略  

3.               threads = malloc(sizeof(LIBEVENT_THREAD) * nthreads);  

4.                if (! threads) {  

5.                    perror("Can't allocate thread descriptors");  

6.                    exit(1);  

7.                }  

8.              

9.                threads[0].base = main_base;  

10.              threads[0].thread_id = pthread_self();  

11.            

12.              for (i = 0; i < nthreads; i++) {  

13.                  int fds[2];  

14.                  if (pipe(fds)) {  

15.                      perror("Can't create notify pipe");  

16.                      exit(1);  

17.                  }  

18.            

19.                  threads[i].notify_receive_fd = fds[0];  

20.                  threads[i].notify_send_fd = fds[1];  

21.            

22.              setup_thread(&threads[i]);  

23.              }  

24.            

25.              /* Create threads after we've done all the libevent setup. */  

26.              for (i = 1; i < nthreads; i++) {  

27.                  create_worker(worker_libevent, &threads[i]);  

28.              }  

29.          }  


threads的声明是这样的 
static LIBEVENT_THREAD *threads; 

thread_init首先malloc线程的空间,然后第一个threads作为主线程,其余都是workers线程 
然后为每个线程创建一个pipe,这个pipe被用来作为主线程通知workers线程有新的连接到达 

看下setup_thread 

C代码 

1.            static void setup_thread(LIBEVENT_THREAD *me) {  

2.                if (! me->base) {  

3.                    me->base = event_init();  

4.                    if (! me->base) {  

5.                        fprintf(stderr, "Can't allocate event base/n");  

6.                        exit(1);  

7.                    }  

8.                }  

9.              

10.              /* Listen for notifications from other threads */  

11.              event_set(&me->notify_event, me->notify_receive_fd,  

12.                        EV_READ | EV_PERSIST, thread_libevent_process, me);  

13.              event_base_set(me->base, &me->notify_event);  

14.            

15.              if (event_add(&me->notify_event, 0) == -1) {  

16.                  fprintf(stderr, "Can't monitor libevent notify pipe/n");  

17.                  exit(1);  

18.              }  

19.            

20.              cq_init(&me->new_conn_queue);  

21.          }  


setup_thread主要是创建所有workers线程的libevent实例(主线程的libevent实例在main函数中已经建立) 

由于之前 threads[0].base = main_base;所以第一个线程(主线程)在这里不会执行event_init() 
然后就是注册所有workers线程的管道读端的libevent的读事件,等待主线程的通知 
最后在该方法里将所有的workersCQ初始化了 

create_worker实际上就是真正启动了线程,pthread_create调用worker_libevent方法,该方法执行 
event_base_loop启动该线程的libevent 

这里我们需要记住每个workers线程目前只在自己线程的管道的读端有数据时可读时触发,并调用 
thread_libevent_process方法 

看一下这个函数 

C代码 

1.            static void thread_libevent_process(int fd, short which, void *arg){  

2.                LIBEVENT_THREAD *me = arg;  

3.                CQ_ITEM *item;  

4.                char buf[1];  

5.              

6.                if (read(fd, buf, 1) != 1)  

7.                    if (settings.verbose > 0)  

8.                        fprintf(stderr, "Can't read from libevent pipe/n");  

9.              

10.              item = cq_peek(&me->new_conn_queue);  

11.            

12.              if (NULL != item) {  

13.                  conn *c = conn_new(item->sfd, item->init_state, item->event_flags,  

14.                                     item->read_buffer_size, item->is_udp, me->base);  

15.                  。。。//省略  

16.              }  

17.          }  



函数参数的fd是这个线程的管道读端的描述符 
首先将管道的1个字节通知信号读出(这是必须的,在水平触发模式下如果不处理该事件,则会被循环通知,直到事件被处理) 

cq_peek是从该线程的CQ队列中取队列头的一个CQ_ITEM,这个CQ_ITEM是被主线程丢到这个队列里的,item->sfd是已经建立的连接 
的描述符,通过conn_new函数为该描述符注册libevent的读事件,me->base是代表自己的一个线程结构体,就是说对该描述符的事件 
处理交给当前这个workers线程处理,conn_new方法的最重要的内容是: 

C代码 

1.            conn *conn_new(const int sfd, const int init_state, const int event_flags,  

2.                            const int read_buffer_size, const bool is_udp, struct event_base *base) {  

3.                。。。  

4.                    event_set(&c->event, sfd, event_flags, event_handler, (void *)c);  

5.                    event_base_set(base, &c->event);  

6.                    c->ev_flags = event_flags;  

7.                    if (event_add(&c->event, 0) == -1) {  

8.                    if (conn_add_to_freelist(c)) {  

9.                        conn_free(c);  

10.                  }  

11.                  perror("event_add");  

12.                  return NULL;  

13.                  }  

14.              。。。  

15.          }  


可以看到新的连接被注册了一个事件(实际是EV_READ|EV_PERSIST,由当前线程处理(因为这里的event_base是该workers线程自己的) 
当该连接有可读数据时会回调event_handler函数,实际上event_handler里主要是调用memcached的核心方法drive_machine 

最后看看主线程是如何通知workers线程处理新连接的,主线程的libevent注册的是监听socket描述字的可读事件,就是说 
当有建立连接请求时,主线程会处理,回调的函数是也是event_handler(因为实际上主线程也是通过conn_new初始化的监听socket libevent可读事件) 

最后看看memcached网络事件处理的最核心部分- drive_machine 
需要铭记于心的是drive_machine是多线程环境执行的,主线程和workers都会执行drive_machine 

C代码 

1.            static void drive_machine(conn *c) {  

2.                bool stop = false;  

3.                int sfd, flags = 1;  

4.                socklen_t addrlen;  

5.                struct sockaddr_storage addr;  

6.                int res;  

7.              

8.                assert(c != NULL);  

9.              

10.              while (!stop) {  

11.            

12.                  switch(c->state) {  

13.                  case conn_listening:  

14.                      addrlen = sizeof(addr);  

15.                      if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {  

16.                          //省去n多错误情况处理  

17.                          break;  

18.                      }  

19.                      if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||  

20.                          fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {  

21.                          perror("setting O_NONBLOCK");  

22.                          close(sfd);  

23.                          break;  

24.                      }  

25.                      dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,  

26.                                               DATA_BUFFER_SIZE, false);  

27.                      break;  

28.            

29.                  case conn_read:  

30.                      if (try_read_command(c) != 0) {  

31.                          continue;  

32.                      }  

33.                  ....//省略  

34.               }       

35.           }  


首先大家不到被while循环误导(大部分做java的同学都会马上联想到是个周而复始的loop)其实while通常满足一个 
case后就会break了,这里用while是考虑到垂直触发方式下,必须读到EWOULDBLOCK错误才可以 

言归正传,drive_machine主要是通过当前连接的state来判断该进行何种处理,因为通过libevent注册了读写时间后回调的都是 
这个核心函数,所以实际上我们在注册libevent相应事件时,会同时把事件状态写到该conn结构体里,libevent进行回调时会把 
conn结构作为参数传递过来,就是该方法的形参 

memcached里连接的状态通过一个enum声明 

C代码 

1.            enum conn_states {  

2.                conn_listening,  /** the socket which listens for connections */  

3.                conn_read,       /** reading in a command line */  

4.                conn_write,      /** writing out a simple response */  

5.                conn_nread,      /** reading in a fixed number of bytes */  

6.                conn_swallow,    /** swallowing unnecessary bytes w/o storing */  

7.                conn_closing,    /** closing this connection */  

8.                conn_mwrite,     /** writing out many items sequentially */  

9.            };  



实际对于case conn_listening:这种情况是主线程自己处理的,workers线程永远不会执行此分支 
我们看到主线程进行了accept后调用了 
  dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,DATA_BUFFER_SIZE, false); 

  这个函数就是通知workers线程的地方,看看 

 

C代码 

1.            void dispatch_conn_new(int sfd, int init_state, int event_flags,  

2.                                   int read_buffer_size, int is_udp) {  

3.                CQ_ITEM *item = cqi_new();  

4.                int thread = (last_thread + 1) % settings.num_threads;  

5.              

6.                last_thread = thread;  

7.              

8.                item->sfd = sfd;  

9.                item->init_state = init_state;  

10.              item->event_flags = event_flags;  

11.              item->read_buffer_size = read_buffer_size;  

12.              item->is_udp = is_udp;  

13.            

14.              cq_push(&threads[thread].new_conn_queue, item);  

15.            

16.              MEMCACHED_CONN_DISPATCH(sfd, threads[thread].thread_id);  

17.              if (write(threads[thread].notify_send_fd, "", 1) != 1) {  

18.                  perror("Writing to thread notify pipe");  

19.              }  

20.          }  



可以清楚的看到,主线程首先创建了一个新的CQ_ITEM,然后通过round robin策略选择了一个thread 
并通过cq_push将这个CQ_ITEM放入了该线程的CQ队列里,那么对应的workers线程是怎么知道的呢 

就是通过这个 
write(threads[thread].notify_send_fd, "", 1 
向该线程管道写了1字节数据,则该线程的libevent立即回调了thread_libevent_process方法(上面已经描述过) 

然后那个线程取出item,注册读时间,当该条连接上有数据时,最终也会回调drive_machine方法,也就是 
drive_machine方法的 case conn_read:等全部是workers处理的,主线程只处理conn_listening 建立连接这个 

这部分代码确实比较多,没法全部贴出来,请大家参考源码,最新版本1.2.6,我省去了很多优化的地方 
比如,每个CQ_ITEMmalloc时会一次malloc很多个,以减小碎片的产生等等细节。 

时间仓促,有纰漏的地方,欢迎大家拍砖。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值