Memcached源码分析(线程模型)

libevent不是多线程安全的,所以memcahced需要自己处理,自己实现http服务器的时候,按照多进程处理,应该比较简单,直接注册accept接受就可以了,即accept是原子的(猜测,需证实)。【修正:accept不是原子的,所以每产生一个可以被accept的连接,会有多个进程或线程被唤醒,但是因为共享一个inode,所以只有一个可以成功accept,其余的返回的fd小于0,可以根据错误码检验问题,是重试还是其他】

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

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

Memcached源码分析(线程模型)


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

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

先看一下大致的图示:


Memcached源码分析(线程模型)

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

C代码  收藏代码

    /* An item in the connection queue. */ 
    typedef struct conn_queue_item CQ_ITEM; 
    struct conn_queue_item { 
        int     sfd; 
        int     init_state; 
        int     event_flags; 
        int     read_buffer_size; 
        int     is_udp; 
        CQ_ITEM *next; 
    }; 



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

C代码  收藏代码

    /* A connection queue. */ 
    typedef struct conn_queue CQ; 
    struct conn_queue { 
        CQ_ITEM *head; 
        CQ_ITEM *tail; 
        pthread_mutex_t lock; 
        pthread_cond_t  cond; 
    }; 



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

C代码  收藏代码

    typedef struct { 
        pthread_t thread_id;        /* unique ID of this thread */ 
        struct event_base *base;    /* libevent handle this thread uses */ 
        struct event notify_event;  /* listen event for notify pipe */ 
        int notify_receive_fd;      /* receiving end of notify pipe */ 
        int notify_send_fd;         /* sending end of notify pipe */ 
        CQ  new_conn_queue;         /* queue of new connections to handle */ 
    } LIBEVENT_THREAD; 



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

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

C代码  收藏代码

    typedef struct{ 
      int sfd; 
      int state; 
      struct event event; 
      short which; 
      char *rbuf; 
      ... //这里省去了很多状态标志和读写buf信息等 
    }conn; 


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

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

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

C代码  收藏代码

    /* initialize main thread libevent instance */ 
     main_base = event_init(); 



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

    /* start up worker threads if MT mode */ 
    thread_init(settings.num_threads, main_base); 


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

    server_socket(settings.port, 0) 


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

然后主线程调用
C代码  收藏代码

    /* enter the event loop */ 
    event_base_loop(main_base, 0); 



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

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

C代码  收藏代码

    void thread_init(int nthreads, struct event_base *main_base) { 
     //。。。省略 
       threads = malloc(sizeof(LIBEVENT_THREAD) * nthreads); 
        if (! threads) { 
            perror("Can't allocate thread descriptors"); 
            exit(1); 
        } 
     
        threads[0].base = main_base; 
        threads[0].thread_id = pthread_self(); 
     
        for (i = 0; i < nthreads; i++) { 
            int fds[2]; 
            if (pipe(fds)) { 
                perror("Can't create notify pipe"); 
                exit(1); 
            } 
     
            threads[i].notify_receive_fd = fds[0]; 
            threads[i].notify_send_fd = fds[1]; 
     
        setup_thread(&threads[i]); 
        } 
     
        /* Create threads after we've done all the libevent setup. */ 
        for (i = 1; i < nthreads; i++) { 
            create_worker(worker_libevent, &threads[i]); 
        } 
    } 


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

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

看下setup_thread

C代码  收藏代码
//回调函数,声明为静待函数
    static void setup_thread(LIBEVENT_THREAD *me) { 
        if (! me->base) { 
            me->base = event_init(); 
            if (! me->base) { 
                fprintf(stderr, "Can't allocate event base\n"); 
                exit(1); 
            } 
        } 
     
        /* Listen for notifications from other threads */ 
        event_set(&me->notify_event, me->notify_receive_fd, 
                  EV_READ | EV_PERSIST, thread_libevent_process, me); 
        event_base_set(me->base, &me->notify_event); 
     
        if (event_add(&me->notify_event, 0) == -1) { 
            fprintf(stderr, "Can't monitor libevent notify pipe\n"); 
            exit(1); 
        } 
     
        cq_init(&me->new_conn_queue); 
    } 


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

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

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

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

看一下这个函数
C代码  收藏代码

    static void thread_libevent_process(int fd, short which, void *arg){ 
        LIBEVENT_THREAD *me = arg; 
        CQ_ITEM *item; 
        char buf[1]; 
     
        if (read(fd, buf, 1) != 1) 
            if (settings.verbose > 0) 
                fprintf(stderr, "Can't read from libevent pipe\n"); 
     
        item = cq_peek(&me->new_conn_queue); 
     
        if (NULL != item) { 
            conn *c = conn_new(item->sfd, item->init_state, item->event_flags, 
                               item->read_buffer_size, item->is_udp, me->base); 
            。。。//省略 
        } 
    } 



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

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

C代码  收藏代码

    conn *conn_new(const int sfd, const int init_state, const int event_flags, 
                    const int read_buffer_size, const bool is_udp, struct event_base *base) { 
        。。。 
                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; 
            } 
        。。。 
    } 


可以看到新的连接被注册了一个事件(实际是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代码  收藏代码

    static void drive_machine(conn *c) { 
        bool stop = false; 
        int sfd, flags = 1; 
        socklen_t addrlen; 
        struct sockaddr_storage addr; 
        int res; 
     
        assert(c != NULL); 
     
        while (!stop) { 
     
            switch(c->state) { 
            case conn_listening: 
                addrlen = sizeof(addr); 
                if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) { 
                    //省去n多错误情况处理 
                    break; 
                } 
                if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || 
                    fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { 
                    perror("setting O_NONBLOCK"); 
                    close(sfd); 
                    break; 
                } 
                dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST, 
                                         DATA_BUFFER_SIZE, false); 
                break; 
     
            case conn_read: 
                if (try_read_command(c) != 0) { 
                    continue; 
                } 
            ....//省略 
         }      
     } 


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

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

memcached里连接的状态通过一个enum声明
C代码  收藏代码

    enum conn_states { 
        conn_listening,  /** the socket which listens for connections */ 
        conn_read,       /** reading in a command line */ 
        conn_write,      /** writing out a simple response */ 
        conn_nread,      /** reading in a fixed number of bytes */ 
        conn_swallow,    /** swallowing unnecessary bytes w/o storing */ 
        conn_closing,    /** closing this connection */ 
        conn_mwrite,     /** writing out many items sequentially */ 
    }; 



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

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


C代码  收藏代码

    void dispatch_conn_new(int sfd, int init_state, int event_flags, 
                           int read_buffer_size, int is_udp) { 
        CQ_ITEM *item = cqi_new(); 
        int thread = (last_thread + 1) % settings.num_threads; 
     
        last_thread = thread; 
     
        item->sfd = sfd; 
        item->init_state = init_state; 
        item->event_flags = event_flags; 
        item->read_buffer_size = read_buffer_size; 
        item->is_udp = is_udp; 
     
        cq_push(&threads[thread].new_conn_queue, item); 
     
        MEMCACHED_CONN_DISPATCH(sfd, threads[thread].thread_id); 
        if (write(threads[thread].notify_send_fd, "", 1) != 1) { 
            perror("Writing to thread notify pipe"); 
        } 
    } 



可以清楚的看到,主线程首先创建了一个新的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_ITEM被malloc时会一次malloc很多个,以减小碎片的产生等等细节。

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

转载地址: http://www.iteye.com/topic/344172

你可能感兴趣的:(memcached)