Memcached data structure the multi-thread of memcached is implemented by instantiating multiple libevent, which is a main thread and n worker threads respectively. Each thread is a separate libevent instance. The main thread eventloop is responsible for listening to fd, listening to client connection requests, and accept connections.
Memcached data structure the multi-thread of memcached is implemented by instantiating multiple libevent, which is a main thread and n worker threads respectively. Each thread is a separate libevent instance. The main thread eventloop is responsible for listening to fd, listening to client connection requests, and accept connections.
Memcached Data Structure
Memcached multithreading is implemented by instantiating multiple libevent, which is a main thread and n worker threads respectively. Each thread is a separate libevent instance. The main thread eventloop is responsible for listening to fd, listening to client connection requests, and accept connections, and connecting established connections to each worker. The workers thread is responsible for handling read/write events of established connections ." One event loop per thread ".
First, let's look at the main data structure.
thread.c
CQ_ITEM is the fd encapsulation that has established a connection returned after the master thread accept.
/* 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 is a one-way linked list for CQ_ITEM management.
/* 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; };
LIBEVENT_THREAD is the encapsulation of the thread structure in memcached. We can see that each thread contains a CQ queue, a notification pipeline pipe, and a libevent instance event_base.
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 encapsulates conn for each network connection
Typedef struct {int sfd; int state; struct event; short which; char * rbuf;... // This saves a lot of status signs and read/write buf information} conn;
Memcached mainly processes events by setting/converting different states of connections (the core function is drive_machine, the connected state machine ).
Memcached thread processing process
Memcached.cMain function, first initialize the libevent instance of the main thread, then Initialize all workers threads, and start. Next, the main thread calls server_socket (this only analyzes the tcp situation) to create a listener socket, bind the address, set the non-blocking mode, and register the libevent read event of the listener socket. Finally, the main thread calls event_base_loop to receive external connection requests.
Main() {/* initialize main thread libevent instance */ main_base = event_init(); /* start up worker threads if MT mode */ thread_init(settings.num_threads, main_base); server_socket(settings.port, 0);/* enter the event loop */ event_base_loop(main_base, 0); }
Finally, let's take a look at the core part of memcached network event processing-drive_machinedrive_machine is executed in a multi-threaded environment, and drive_machine is executed in both the main thread and workers.
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) {// saves n multiple error handling 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;}... // omitted }}
Drive_machine mainly determines the processing method through the state of the current connection, because the core function is called back after the read/write event is registered through libevent, so when we register the corresponding libevent event, the event state is written to the conn struct. When the libevent calls back, the conn structure is passed as a parameter, which is the form parameter of the method. The following lists the connection statuses.
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 */ };
Actual case conn_listening: In this case, the main thread processes the job itself, and the workers thread will never execute this branch. We can see that the master thread has performed accept and called
dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,DATA_BUFFER_SIZE, false);
This function is the place to notify the workers thread.
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"); } }
It can be clearly seen that the main thread first creates a new CQ_ITEM, then selects a thread through the round robin policy, and puts the CQ_ITEM into the CQ queue of the thread through cq_push, so how does the corresponding workers thread know? Is through
write(threads[thread].notify_send_fd, "", 1)
If 1 byte of data is written to the thread pipeline, the libevent of the thread immediately calls back the thread_libevent_process method (as described above ). Then the thread retrieves the item and registers the read time. When there is data on the connection, the thread will also call back the drive_machine method, that is, the case conn_read of the drive_machine method: the main thread only processes conn_listening to establish a connection. This multi-thread event mechanism of memcached is worthy of reference when designing linux backend network programs.
References
- Memcache source code analysis-thread model
- Memcached Structure Analysis-thread model
- Memcached thread model and state machine
Original article address: memcached thread model. Thank you for sharing it.