多读多写 无锁 lifo 队列

多读多写下,先进后出队列,可以不加锁,下面是实现代码 lifo.h

#include "cas.h"
#include <stddef.h>

struct lifo_node
{
    volatile struct lifo_node *next;
};

struct lifo
{
void init() {
    top = NULL;
    cnt=0;
}

void push(lifo_node *node) {
   struct lifo old_val, new_val;
   do {
     old_val = *this;
     node->next = old_val.top;
     new_val.top = node;
     new_val.cnt = old_val.cnt;
   }while(!CAS2(this, old_val, new_val));
}
 
lifo_node * pop() {
   struct lifo_node *node;
   struct lifo old_val, new_val;
   do {
     old_val = *this;
     node = old_val.top;
     new_val.top = old_val.top;
     new_val.cnt = old_val.cnt+1;
   }while(!CAS2((this), old_val, new_val));
   return node;
}

struct lifo_node * volatile top;
volatile unsigned int cnt;
};

posted @ 2011-04-06 10:25  napoleon_liu  阅读(2357)  评论(0编辑  收藏  举报