无锁循环队列

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdatomic.h>

// 定义数据类型
typedef int ElemType;

// 定义循环队列类
typedef struct {
    ElemType *elems;    // 存储队列元素的指针
    _Atomic int front;  // 队首指针
    _Atomic int rear;   // 队尾指针
    _Atomic int count;  // 队列中元素的个数
    int max_count;      // 队列最大容量
} CircleQueue;

// 初始化循环队列
void initQueue(CircleQueue *q, int max_count) {
    q->elems = (ElemType *)malloc(max_count * sizeof(ElemType));
    atomic_init(&q->front, 0);
    atomic_init(&q->rear, 0);
    atomic_init(&q->count, 0);
    q->max_count = max_count;
}

// 销毁循环队列
void destroyQueue(CircleQueue *q) {
    free(q->elems);
    atomic_store(&q->front, 0);
    atomic_store(&q->rear, 0);
    atomic_store(&q->count, 0);
    q->max_count = 0;
}

// 判断队列是否为空
bool isEmpty(CircleQueue *q) {
    return atomic_load(&q->count) == 0;
}

// 判断队列是否已满
bool isFull(CircleQueue *q) {
    return atomic_load(&q->count) == q->max_count;
}

// 入队操作
bool enqueue(CircleQueue *q, ElemType e) {
    if (isFull(q)) {
        printf("队列已满,无法入队!\n");
        return false;
    }
    int rear = atomic_load(&q->rear);
    q->elems[rear] = e;
    atomic_store(&q->rear, (rear + 1) % q->max_count);
    atomic_fetch_add(&q->count, 1);
    return true;
}

// 出队操作
bool dequeue(CircleQueue *q, ElemType *e) {
    if (isEmpty(q)) {
        printf("队列为空,无法出队!\n");
        return false;
    }
    int front = atomic_load(&q->front);
    *e = q->elems[front];
    atomic_store(&q->front, (front + 1) % q->max_count);
    atomic_fetch_sub(&q->count, 1);
    return true;
}

// 测试循环队列的代码
int main() {
    CircleQueue q;
    int max_count = 5;  // 队列最大元素个数
    initQueue(&q, max_count);  // 初始化队列
    for (int i = 1; i <= max_count + 1; i++) {
        if (!enqueue(&q, i)) {
            printf("第%d个元素入队失败!\n", i);
        }
    }
    ElemType e;
    while (!isEmpty(&q)) {
        dequeue(&q, &e);
        printf("%d ", e);
    }
    printf("\n");
    destroyQueue(&q);  // 销毁队列
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值