数组实现线程安全的循环队列
cas函数如下:bool succ = __sync_bool_compare_and_swap(&a, b, c)
struct queue{
int data[10000];
int front;
int back;
};
int maxSize=10000;
queue* q;
int push(int d){
if ((q->back+1)%maxSize==q->front)
return -1;
q->data[back]=d;
q->back=(q->back+1)%maxSize;
return 0;
}
int pop(int &d){
if(q->front==q->back) return -1;
d=q->data[q->front];
q->front=(q->front+1)%maxSize;
return 0;
}
int pop2(int& d){
int temp=q->front;
if (temp==q->back)
return -1;
d=q->data[temp];
while(!__sync_bool_compare_and_swap(q->front,temp,(temp+1)%maxSize))
{
temp=(temp+1)%maxSize;
}
return 0;
}
数组实现线程安全的栈
int stack[10000];
int maxSize=10000;
int top=-1;
int push(int number)
{
if(top>=maxSize)
{
return -1;
}else{
top++;
stack[top]=number;
}
}
int pop(int &d)
{
if(top<0)
{
return -1;
}else{
d=stack[top];
top--;
}
}
int pop2(int &d)
{
int temp=top;
if(temp<0)
{
return -1;
}
d=stack[temp];
while(!__sync_bool_compare_and_swap(top,temp,temp--)
{
temp--;
}
return 0;
}