zoukankan      html  css  js  c++  java
  • Kernel list_head demo实现

    内核中很多地方用到队列,如果每一个数据结构都实现一个双向队列,并针对这些数据结构实现对应的操作,那么代码将会非常冗余,于是内核抽象出了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有写技术博客,但是发觉并不是太好,又辗转至此。

  • 相关阅读:
    常用博客Metaweblog Api地址
    如何在Mac下配置Github和Bitbucket的SSH
    Java内部类持有外部类的引用详细分析与解决方案
    java 静态变量生命周期(类生命周期)
    比较List和ArrayList的性能及ArrayList和LinkedList优缺点
    List和ArrayList的区别
    hashmap可以用null为键值
    iOS各种调试技巧豪华套餐
    Split()[1]中的[1]是什么意思
    windows安装TortoiseGit详细使用教程
  • 原文地址:https://www.cnblogs.com/zhouyongtao/p/4899965.html
Copyright © 2011-2022 走看看