linux核心鍊錶用於專案中的演練

2021-07-10 19:02:49 字數 2427 閱讀 2218

main.c:

#include 

#include "list.h"

typedef

struct filefilex,*pfilex;

int main()

printf("*******************\n");

list_del(&file_b.list);

list_for_each_entry(file_tmp, &head, list)

list_del(&file_a.list);

list_del(&file_c.list);

if (list_empty(&head))

else

printf("hello world!!!\n");

return

0;}

list.h ==>來自linux核心

#ifndef _linux_list_h

#define _linux_list_h

#define list_poison1 ((void *) 0x00100100)

#define list_poison2 ((void *) 0x00200200)

//typedef unsigned int size_t;

static inline void prefetch(const

void *x)

#define offsetof(type, member) ((size_t) &((type *)0)->member)

#define container_of(ptr, type, member) ()

struct list_head ;

#define list_head_init(name)

#define list_head(name) \

struct list_head name = list_head_init(name)

#define init_list_head(ptr) do while (0)

static inline void __list_add(struct list_head *new,

struct list_head *prev,

struct list_head *next)

/** * 把元素插入特定元素之後

*/static inline void list_add(struct list_head *new, struct list_head *head)

static inline void __list_del(struct list_head * prev, struct list_head * next)

/** * 刪除特定元素

*/static inline void list_del(struct list_head *entry)

/** * 檢查指定的鍊錶是否為空

*/static inline int list_empty(const struct list_head *head)

/**

* 返回鍊錶所在結構

*/#define list_entry(ptr, type, member) \

container_of(ptr, type, member)

/** * 掃瞄指定的鍊錶

*/#define list_for_each(pos, head) \

for (pos = (head)->next; prefetch(pos->next), pos != (head); \

pos = pos->next)

/** * 與list_for_each相似,但是返回每個鍊錶結點所在結構

*/ #define list_for_each_entry(pos, head, member) \

for (pos = list_entry((head)->next, typeof(*pos), member); \

prefetch(pos->member.next), &pos->member != (head); \

pos = list_entry(pos->member.next, typeof(*pos), member))

#endif

main.c的輸出

[root@localhost test]# gcc main.c

[root@localhost test]# ./a.out

1020

30*******************

1030

list is empty!!!

hello world!!!

[root@localhost test]#

可以將上面的內容用於生產與消費者,加上malloc,free。動態生產與消費。

linux核心鍊錶

鍊錶是一種常用的資料結構,它通過指標將一系列資料節點連線成一條資料鏈。相對於陣列,鍊錶具有更好的動態性,建立鍊錶時無需預先知道資料總量,可以隨機分配空間,可以高效地在鍊錶中的任意位置實時插入或刪除資料。鍊錶的開銷主要是訪問的順序性和組織鏈的空間損失。一 鍊錶結構 單鏈表結構如下 雙鏈表結構如圖 st...

linux核心鍊錶

include include struct list head struct mylist void list add struct list head new,struct list head prev,struct list head next void list add tail struc...

Linux核心鍊錶

核心鍊錶 核心鍊錶即,我麼在乙個鍊錶中插入或刪除乙個資料,都需要自己編寫 相當的麻煩,怎麼解決這個問題呢,為了更加方便的解決這個問題,linux中就產生了核心鍊錶,以後想要在鍊錶中插入資料或刪除資料時,只需要呼叫函式就可以了。鍊錶對比 鍊錶是一種資料結構,他通過指標將一系列的資料節點連線成一條資料鏈...