利用CAS和数组实现线程安全的栈和循环队列

数组实现线程安全的循环队列

cas函数如下:bool succ = __sync_bool_compare_and_swap(&a, b, c) 
 //---》 if(a ==b ) {a = c;return true;}else{return false}
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){
    
    	//cas
        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) //cas
{
    
     
   int temp=top;
   if(temp<0) 
   {
    
     
       return -1; 
   }
   d=stack[temp]; 
   while(!__sync_bool_compare_and_swap(top,temp,temp--)
    {
    
    
      temp--;
    }     
   return 0;
} 

猜你喜欢

转载自blog.csdn.net/u014618114/article/details/108125101