Source code analysis Redis underlying data structure - linked list

definition

As a commonly used data structure, linked list is built in many advanced programming languages, such as: java; because Redis is developed in C language, but there is no built-in linked list data structure in C language, so Redis built its own linked list implementation .

Each linked list node is represented by a adlist.h/listNodestructure :

/* Node, List, and Iterator are the only data structures used currently. */

typedef struct listNode {
    struct listNode *prev;
    struct listNode *next;
    void *value;
} listNode;

Multiple listNodecan form a double-ended linked list through prevand nextpointers , as shown in the following figure:

insert image description here

A linked list can contain multiple linked list nodes, adlist.h/list

/*
 * 双端链表结构
 */
typedef struct list {

    // 表头节点
    listNode *head;

    // 表尾节点
    listNode *tail;

    // 节点值复制函数
    void *(*dup)(void *ptr);

    // 节点值释放函数
    void (*free)(void *ptr);

    // 节点值对比函数
    int (*match)(void *ptr, void *key);

    // 链表所包含的节点数量
    unsigned long len;
} list;

list 结构为链表提供了表头指针head 、表尾指针tail, and the length counter len of the linked list, while the dup and free match` members are type-specific functions required to implement polymorphic linked lists:

  • dupThe function is used to copy the value saved by the linked list node;
  • freeThe function is used to release the value saved by the linked list node;
  • matchThe function is used to compare whether the value stored by the linked list node is equal to another input value.

Summarize

  • Linked lists are widely used to implement various functions of Redis, such as list keys, publish and subscribe, slow query, monitor, etc.
  • Each linked list node is represented by a listNodestructure , and each node has a pointer to the preceding node and the following node, so the linked list implementation of Redis is a double-ended linked list.
  • Each linked list is represented by a liststructure , which has information such as the head node pointer, the tail node pointer, and the length of the linked list.
  • Because the front node of the head node of the linked list and the post node of the tail node both point to it NULL, the linked list implementation of Redis is an acyclic linked list.
  • By setting different type-specific functions for linked lists, Redis linked lists can be used to store values ​​of various types.

Guess you like

Origin blog.csdn.net/m0_54369189/article/details/113703527