无锁队列

到时候再改!

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

typedef char elem_type;

#define _CAS_ 5


struct queue{
    int start;
    int end;
    int size;
    elem_type *buffer;
};

#define is_full(q) \
        (((q).end + 1) % ((q).size) == ((q).start))

#define is_empty(q) \
        ((q).end == (q).start)

void queue_init(struct queue *q,int size){
    assert(q);

    q->start = q->end = 0;
    q->size = size;
    q->buffer = (elem_type *)malloc(sizeof(elem_type)*size);
    if(q->buffer == NULL)
        return;
}

void queue_add(struct queue *q,elem_type e){
    assert(q);
    assert(e);

    q->buffer[q->end] = e;
    q->end = (q->end + 1) % q->size;
}

void queue_sub(struct queue *q,elem_type *e){
    assert(q);
    assert(e);

    *e = q->buffer[q->start];
    q->start = (q->start + 1) % q->size;
}

int queue_add_cas(struct queue *q,elem_type e){
    int cnt = 0;

    assert(q);
    assert(e);
    
    while(is_full(*q)){
        if(++cnt > _CAS_)
            return -1;
    }

    queue_add(q,e);
    return 0;
}

int queue_sub_cas(struct queue *q,elem_type *e){
    int cnt = 0;

    assert(q);
    assert(e);
    
    while(is_empty(*q)){
        if(++cnt > _CAS_)
            return -1;
    }
    queue_sub(q,e);
    return 0;
}

void queue_free(struct queue *q){
    if(q->buffer)
        free(q->buffer);
    if(q)
        free(q);
}
int main()
{
    int i = 0;
    elem_type data;
    struct queue q;

    queue_init(&q,100);
    for(i=0;i<100;i++){
        if(is_full(q)){
            printf("%d is full\n",i);
                break;
        }
        printf("%d if not full\n",i);
        data = i+1;
        queue_add_cas(&q,data);
    }

    for(i=0;i<100;i++){
        if(is_empty(q)){
            printf("%d is empty\n",i);
                break;
        }
        queue_sub_cas(&q,&data);
        printf("%d,%d if not empty\n",i,data);
    }
    //queue_free(&q);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值