Linux内核队列——kfifo

来源:互联网 发布:淘宝精品推荐怎么进 编辑:程序博客网 时间:2024/05/16 10:14

kfifo概述

Linux内核里有许多优美的数据结构,队列kfifo就是其中之一。kfifo是内核里面的一个First In First Out数据结构,它采用环形循环队列的数据结构来实现;它提供一个无边界的字节流服务,最重要的一点是,它使用并行无锁编程技术,即当它用于只有一个入队线程和一个出队线程的场情时,两个线程可以并发操作,而不需要任何加锁行为,就可以保证kfifo的线程安全。

结构体kfifo的定义

在Linux2.6版本及之前的内核版本中,kfifo的定义如下:

struct kfifo {       unsigned char *buffer;    /* the buffer holding the data */       unsigned int size;    /* the size of the allocated buffer */       unsigned int in;    /* data is added at offset (in % size) */       unsigned int out;    /* data is extracted from off. (out % size) */       spinlock_t *lock;    /* protects concurrent modifications */   }; 

但在现在新的内核版本中已经找不到这个定义了,而且kfifo的定义还有点隐藏性,以下是linux-3.19.2里kfifo.h文件里kfifo的定义:

#define __STRUCT_KFIFO_COMMON(datatype, recsize, ptrtype) \    union { \        struct __kfifo  kfifo; \        datatype    *type; \        const datatype  *const_type; \        char        (*rectype)[recsize]; \        ptrtype     *ptr; \        ptrtype const   *ptr_const; \    }#define __STRUCT_KFIFO_PTR(type, recsize, ptrtype) \{ \    __STRUCT_KFIFO_COMMON(type, recsize, ptrtype); \    type        buf[0]; \}/* * define compatibility "struct kfifo" for dynamic allocated fifos */struct kfifo __STRUCT_KFIFO_PTR(unsigned char, 0, void);

经过几个宏定义转换后,可以得到kfifo的定义如下:

struct kfifo {    union{        struct __kfifo kfifo;        unsigned char *type;        const unsigned char *const_type;        char (*rectype)[0];        void *ptr;        void const *ptr_const;    }    unsigned char buf[0];};

其中结构体__kfifo的定义如下:

struct __kfifo {    unsigned int    in;    unsigned int    out;    unsigned int    mask;    unsigned int    esize;    void        *data;};

kfifo相关操作

原文地址1:http://blog.csdn.net/linyt/article/details/5764312
原文地址2:http://blog.csdn.net/zmrlinux/article/details/48601877

0 0
原创粉丝点击