无锁队列

工程里面有很多单生产单消费模型的线程;所以加入无锁队列.提高整体的速度;

串口资料如下.

http://blog.csdn.net/linyt/article/details/53355355

http://www.cnblogs.com/madao/archive/2013/03/06/2943467.html

 

代码如下:

#define QUEUE_SIZE 1024
typedef unsigned int ElementType;

struct kfifo
{
    ElementType data[ QUEUE_SIZE ];
    unsigned int in; 
    unsigned int out;
};

int kfifo_put( struct kfifo *fifo, ElementType element )
{
    if ( QUEUE_SIZE - fifo->in + fifo->out == 0 )
        return 0;

    __sync_synchronize();      //确保取出的out是最新的(它是这么说的,但极度怀疑不需要)

    unsigned int index = fifo->in & (QUEUE_SIZE - 1);
    fifo->data[ index ] = element;

    __sync_synchronize();      //确保先写入数据再更新in

    fifo->in++;

    return 1;
}

int kfifo_get( struct kfifo *fifo, ElementType *element )
{
    if ( fifo->in - fifo->out == 0 )
        return 0;
    unsigned int index = fifo->out & (QUEUE_SIZE - 1);

    __sync_synchronize();       //确保读出的in是最新的(同上)

    *element = fifo->data[ index ];

    __sync_synchronize();       //确保先读取数据再更新out

    fifo->out++;

    return 1;
}

需要注意到:

1.QUEUE_SIZE = 2^n



posted @ 2017-03-10 17:32  码工木木  阅读(411)  评论(0编辑  收藏  举报