I shared some personal opinions about memcache with my colleagues in the company last week and sorted it out later. It mainly consists of the network thread model, basic memory structure, LRU structure, hash conflicts, and hash Qiankun big migration.
MEmcache is a single-process multi-thread structure, the communication framework uses libevent (http://monkey.org /~ Provos/libevent/manages the timer, pipeline, socket, and interrupt operations in a unified manner. The rich functions certainly bring some performance side effects,CodeIt is worth reading and Learning ).
1. There are two types of threads: main thread (receiving thread) and working thread:
1) after the main thread completes some initialization of memcache, it starts the event_base_loop and starts to monitor and accept the new connection. After receiving the new connection, the main thread passes round training, allocate new connection to the corresponding thread (of course, the worker thread is also started by the main thread, or who else will start the worker thread );
2) After the worker thread accepts the new connection from the master thread, it adds the new connection to the listening queue to complete all subsequent data communication work, for example, set, get, and del data based on client commands must be completed in the working thread (the listening method of the working thread is also an event_base_loop loop );
2. Main thread and working thread socket Transmission
The method for allocating new connect to the main thread is loop;
Key code: int tid = (last_thread + 1) % settings. num_threads; select the corresponding worker thread based on the calculated value
The main thread and the working thread use a conn_queue_item when passing the socket handle. Each working thread corresponds to a conn_queue to accept the conn_queue_item allocated by the main thread. The main thread first obtains a conn_queue_item element from the Free List of conn_queue_item, fills in the corresponding information and stores it in the message queue of the working thread, and then uses the pipeline working thread to handle new connections.
Key code:
1) Obtain an empty element from the idle linked list
If (cqi_freelist ){
Item = cqi_freelist;
Cqi_freelist = item-> next;
}Else {
New cqi_freelist
}
2) added to the working thread queue and MPs queue notifications
If (null = CQ-> tail)
CQ-> head = item;
Else
CQ-> tail-> next = item;
Write (pipefd)
3) The worker thread processes new connections.
Item = CQ-> head;
If (null! = Item ){
CQ-> head = item-> next;
If (null = CQ-> head)
CQ-> tail = NULL;
}
Free (item)
New Connection allocation processing Flowchart