内核中很多地方用到队列,如果每一个数据结构都实现一个双向队列,并针对这些数据结构实现对应的操作,那么代码将会非常冗余,于是内核抽象出了list_head数据结构,并文参考内核中的代码写成,实现了一个list_head demo。
#include <iostream> #include <stdint.h> using namespace std; #define list_entry(ptr, type, member) \ ( (type *) ((char *)(ptr) - (unsigned long)(&((type *)0)->member))) struct list_head { struct list_head *prev, *next; }; inline void init_list_head (struct list_head *ptr) { ptr->prev = ptr; ptr->next = ptr; } inline void __list_add (struct list_head *prev, struct list_head *next, struct list_head *node) { prev->next = node; next->prev = node; node->prev = prev; node->next = next; } inline void list_add (struct list_head *head, struct list_head *node) { __list_add (head, head->next, node); } inline void __list_del (struct list_head *prev, struct list_head *next) { next->prev = prev; prev->next = next; } inline void list_del (struct list_head *node) { __list_del (node->prev, node->next); } struct page { int32_t id; struct list_head lru; page(int32_t pid) : id(pid) {} }; struct list_head pageLRUList; int main () { init_list_head(&pageLRUList); int i; for (i = 0; i < 3; i++) { struct page *tmpPage = new struct page(i); list_add(&pageLRUList, &tmpPage->lru); } struct list_head *tmpPtr = &pageLRUList; for (i = 0; i < 3; i++) { tmpPtr = tmpPtr->next; struct page *tmpPage = list_entry(tmpPtr, struct page, lru);//(struct page *)((char*)(tmpPtr) - (unsigned long)(&((struct page*)0)->lru)); cout << tmpPage->id << endl; } return 0; }
#后记,很久没有写博客了,之前在点点,lofter有写技术博客,但是发觉并不是太好,又辗转至此。