Linux 內核雙向鏈表 list_head

舉個栗子

struct student { // 學生
    int id; // 學號
    int score; // 分數
    struct student *next, *prev;
}

struct student 可以表示一個學生的鏈表(將一個個學生鏈起來),成員變量 *next、*prev 可以表示前和後的指針

一、雙向鏈表 list_head

struct list_head {
	struct list_head *next, *prev;
};

問題 1:list_head 既然是雙向鏈表,鏈接的數據是什麼,在哪裏?

struct student 有一個分別指向前後的指針
struct list_head 有一個分別指向前後的指針
使用 struct list_head list; 替換 struct student *next, *prev;

struct student { // 學生
    int id; // 學號
    int score; // 分數
    struct list_head list;
}

問題 2:真的能用 struct list_head 替換 struct student 嗎?

問題 1、2 的
解:list_head 作爲 student 的成員,通過 list_head 的地址可以獲得 student 的地址(關鍵就是 list_entry 宏)

1.1 宏 list_entry

/**
 * list_entry - 獲取給定 list_head 成員的宿主結構 entry
 * @ptr:	類型是 struct list_head(指向成員 member 的指針)
 * @type:	宿主容器結構的類型
 * @member:	內部的 list_head 的變量名字(成員 member 的名稱),類型是 struct list_head
 */
#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)

1.2 宏 container_of

/**
 * container_of - 將成員 member 的地址強制轉換爲該包含該成員 member 的結構的地址,即實現上面 "問題 2" 的功能
 * @ptr:	指向成員 member 的指針
 * @type:	成員 member 所嵌入的宿主容器結構的類型
 * @member:	結構中成員 member 的名稱
 */
#define container_of(ptr, type, member) ({			\
    const typeof(((type *)0)->member) * __mptr = (ptr);	\
    (type *)((char *)__mptr - offsetof(type, member)); })

先看第一行代碼

(type *)((char *)__mptr - offsetof(type, member));

第一行代碼的作用是獲取結構體 member 的地址(通過 member 的地址可以算出包含該成員 member 的結構的地址)

問:ptr 的註釋是:the pointer to the member,爲什麼還要轉爲 member 類型的 __mptr?
答:使用 __mptr 的目的是在編譯期間進行類型檢測(第一句,賦值時如果類型不匹配會報告警),保證傳入的成員地址與成員類型是匹配的,而在運行期間則和忽略中間變量 __mptr 是一樣的

第二行代碼

(type *)((char *)__mptr - offsetof(type, member));

1.3 宏 offsetof(type, member)

還是一個宏,解釋一下 offsetof(type, member) 的含義

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  • (TYPE *)0
    把 0 地址轉(結構體起始地址)爲 TYPE 指針
  • &((TYPE *)0)->MEMBE
    優先級:& 小於 ->,獲取 TYPE 的 MEMBER 的地址
  • (size_t) &((TYPE *)0)->MEMBER
    將 MEMBER 的地址強制轉爲 size_t(int)型

offsetof 的作用是獲取 MEMBER 在 TYPE 中的偏移量

offsetof 獲取 MEMBER 在 TYPE 中的偏移量

再次看一下第二行代碼

(type *)((char *)__mptr - offsetof(type, member));
  • (char )__mptr
    這裏要將結構體 member 的地址轉爲 char
    類型,原因是指針在計算偏移,非指針加減(加減移動 4 字節),內存的最小單位是字節,轉爲 char* 符合要求
  • offsetof(type, member)
    MEMBER 在 TYPE 中的偏移量
  • (type *)((char )__mptr - offsetof(type, member))
    (type
    )(結構體 member 的地址 - MEMBER 在 TYPE 中的偏移量) = 包含成員 member 的結構的地址

第二行代碼的作用是獲取包含 member 的那個含有真實數據的結構體的地址,即通過指向結構體成員 member 的指針 ptr 獲取指向整個結構體的指針

通過指向結構體成員 member 的指針 ptr 獲取指向整個結構體的指針

二、相關操作

2.1 聲明和初始化鏈表

// 僅初始化:將 name 的地址直接分別賦值給 next 和 prev,都指向自己
#define LIST_HEAD_INIT(name) { &(name), &(name) }

// 聲明並初始化:定義鏈表頭 name(頭結不使用,不帶有效數據),通過 LIST_HEAD_INIT 初始化雙向循環鏈表爲空
#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

list_head 默認爲空鏈表(前後指針都初始化爲指向自己)

2.2 鏈表判空

函數前關鍵字 static:靜態函數,限制函數作用域(static 函數作用域僅限本文件),具有信息隱藏的作用
函數前關鍵字 inline:對編譯程序可見,即編譯程序在調用函數時會立即展開函數

static inline int list_empty(const struct list_head *head) {
    return head->next = head;
}

2.3 添加元素

// 頭插(相當於棧)
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next); // 把新項 new 添加到 head 之後
}

// 尾插(相當於隊列)
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head); // 把新項 new 添加到 head 之前
}

通用插入函數:__list_add(下劃線開始的函數用於內部調用)

static inline void __list_add(struct list_head *new, struct list_head *prev, struct list_head *next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

list_add:
list_add

list_add_tail:
list_add_tail

2.4 刪除元素

static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    entry->next = LIST_POISON1;
    entry->prev = LIST_POISON2;
}

static inline void list_del_init(struct list_head *entry)
{
    __list_del_entry(entry);
    INIT_LIST_HEAD(entry);
}

static inline void __list_del_entry(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
}

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

通用刪除函數:__list_del(下劃線開始的函數用於內部調用)

static inline void __list_del(struct list_head * prev, struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}

list_del 和 list_del_init:
list_del 和 list_del_init

2.5 修改元素

static inline void list_replace(struct list_head *old, struct list_head *new)
{
    new->next = old->next;
    new->next->prev = new;
    new->prev = old->prev;
    new->prev->next = new;
}

static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
    list_replace(old, new);
    INIT_LIST_HEAD(old);
}

list_replace 和 list_replace_init

2.6 遍歷元素

list_for_each、list_for_each_safe:獲取節點 pos 在鏈表中的偏移位置

// pos:指向宿主結構的指針(如:student)
// head:進行遍歷的鏈表頭指針
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

// list_for_each:若當前 pos 指向的元素被刪除,pos 的指向就會改變,就無法再通過 pos->next 指向鏈表的後續元素,可以選擇安全的 list_for_each_safe

// safe 體現在哪?
// 這裏的 pos 和 n 關係爲:n = pos->next,若當前 pos 指向的元素被刪除,pos 的指向就會改變,但此時依然可以通過 n 標識被刪元素的下一個元素
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

list_for_each_entry:遍歷給定類型的列表

// pos:指向宿主結構的指針(如:student)
// head:進行遍歷的鏈表頭指針
// member:list_head 成員在宿主結構中的名字
#define list_for_each_entry(pos, head, member)				\
    for (pos = list_entry((head)->next, typeof(*pos), member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.next, typeof(*pos), member))

list_entry,在上面 1.1 處已經解釋過

/**
 * list_entry - 獲取給定 list_head 成員的宿主結構 entry
 * @ptr:	類型是 struct list_head(指向成員 member 的指針)
 * @type:	宿主容器結構的類型
 * @member:	內部的 list_head 的變量名字(成員 member 的名稱),類型是 struct list_head
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

回顧 list_entry 結論:通過指向結構體成員 member 的指針 ptr 獲取指向整個結構體的指針(如:根據一個結構體變量中的一個域成員變量 list_head 的指針來獲取宿主容器結構 student 的指針)

三、使用方式

在 C++ 中使用 Linux 內核雙向鏈表 list_head

3.1 my_list.h(參照 Linux 的 list.h 代碼)

#ifndef _LINUX_LIST_H
#define _LINUX_LIST_H

#include <iostream>
#include <time.h>

struct list_head {
    struct list_head *next, *prev;
};

#define container_of(ptr, type, member) \
    ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

static inline void __list_add(struct list_head *new_obj,
					struct list_head *prev,
					struct list_head *next)
{
	next->prev = new_obj;
	new_obj->next = next;
	new_obj->prev = prev;
	prev->next = new_obj;
}

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void list_add(struct list_head *new_obj, struct list_head *head)
{
    __list_add(new_obj, head, head->next);
}

/**
 * list_for_each	-	iterate over a list
 * @pos:	the &struct list_head to use as a loop cursor.
 * @head:	the head for your list.
 */
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)

/**
 * list_entry - get the struct for this entry
 * @ptr:	the &struct list_head pointer.
 * @type:	the type of the struct this is embedded in.
 * @member:	the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

/**
 * list_for_each_entry	-	iterate over list of given type
 * @pos:	the type * to use as a loop cursor.
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
// list_entry 第二個參數這裏寫死了 struct student(本來是 typeof(*pos))暫時不知道怎麼動態傳類型
#define list_for_each_entry(pos, head, member)				\
    for (pos = list_entry((head)->next, struct student, member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.next, struct student, member))

/**
 * list_for_each_entry_reverse - iterate backwards over list of given type.
 * @pos:	the type * to use as a loop cursor.
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
// list_entry 第二個參數這裏寫死了 struct student(本來是 typeof(*pos))暫時不知道怎麼動態傳類型
#define list_for_each_entry_reverse(pos, head, member)			\
    for (pos = list_entry((head)->prev, struct student, member);	\
        &pos->member != (head); 	\
        pos = list_entry(pos->member.prev, struct student, member))

/**
 * list_for_each_safe - iterate over a list safe against removal of list entry
 * @pos:	the &struct list_head to use as a loop cursor.
 * @n:		another &struct list_head to use as temporary storage
 * @head:	the head for your list.
 */
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

/**
 * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
 * @pos:	the type * to use as a loop cursor.
 * @n:		another type * to use as temporary storage
 * @head:	the head for your list.
 * @member:	the name of the list_struct within the struct.
 */
#define list_for_each_entry_safe(pos, n, head, member)			\
    for (pos = list_entry((head)->next, struct student, member),	\
        n = list_entry(pos->member.next, struct student, member);	\
        &pos->member != (head); 					\
        pos = n, n = list_entry(n->member.next, struct student, member))

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	prev->next = next;
}

static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = NULL;
	entry->prev = NULL;
}

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static inline int list_empty(const struct list_head *head)
{
	return head->next == head;
}

#endif

3.2 main.cpp

// List.cpp: 定義應用程序的入口點。
//

#include "my_list.h"

#define random() (rand() % (100 - 60 + 1)+ 60) // 隨機數生成範圍:[60, 100]

using namespace std;

struct student
{
    int id; // 學號
    int score; // 分數
    struct list_head list;
};

int main()
{
	// 根據運行程序的時間產生不同的隨機數種子
	srand((unsigned)time(NULL));

    // 初始化鏈表
    //struct student stu_head;
    //INIT_LIST_HEAD(&stu_head.list);
    
    LIST_HEAD(stu_head);

    // 添加元素
    int i;
    struct student *stu;
    for (i = 0; i < 5; i++)
    {
        stu = (struct student*)malloc(sizeof(student));
        stu->id = i + 1;
        stu->score = random();
        
        // 添加 stu 到鏈表中(先加入的 stu,後打印)
        list_add(&stu->list, &stu_head);
    }

    cout << "打印元素" << endl;
    
    struct list_head *pos;
    list_for_each(pos, &stu_head) {
        stu = list_entry(pos, struct student, list);
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }
    
    cout << "鏈表是否爲空:" << list_empty(&stu_head) << endl;
    
    cout << "---------華麗的分割線---------" << endl;
    
    // 翻轉鏈表
    list_for_each_entry_reverse(stu, &stu_head, list) {
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }

    /*
    // 通過 entry 遍歷元素,不用再每次循環都執行一次 list_entry
    list_for_each_entry(stu, &stu_head, list) {
        cout << "id=" << stu->id << ", " << "score=" << stu->score << endl;
    }
    */

    /*
    // 刪除元素
    struct list_head *n;
    list_for_each_safe(pos, n, &stu_head) {
    stu = list_entry(pos, struct student, list);
    list_del(pos);
    free(stu);
    }
    */

    struct student *n;
    list_for_each_entry_safe(stu, n, &stu_head, list) {
        list_del(&stu->list);
        free(stu);
    }

    cout << "鏈表是否爲空:" << list_empty(&stu_head) << endl;

    getchar();
    return 0;
}

3.3 運行一下,看看結果

控制檯打印結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章