利用环形队列+CAS实现无锁队列

利用环形队列+CAS实现无锁队列

优点:

1.保证元素的先进先出

2.元素空间可以重复利用,因为是环形的。

3.为多线程数据通信提供了一种高效的机制,比BlockingQueue速度要快。

下面提供一种Java实现:

public class LockFreeQueue {
  private AtomicReferenceArray atomicReferenceArray;
  priviate final Integer EMPTY = null;
  private AtomicInteger head,tail;
  public LockFreeQueue(int size) {
    //空出一个位置 用于判断队列满或空 tail==head时为空 (tail+1)%len==head为满
  	atomicReferenceArray = new AtomicRefrenceArray(new Integer[size + 1]);
    head = new AtomicInteger(0);
    tail = new AtomicInteger(0);
  }
  
  public boolean add(Integer element) {
  	int index = (tail.get() + 1% atomicReferenceArray.length();
    if (index == head.get()) {
      System.out.println("队列已满")return false;
    }
    while(!atomicReferenceArray.compareAndSet(index,EMPTY,element)) {
      return add(element);
	}
    tail.incrementAndGet();
    System.out.println("入队成功")return true;
  }
  
  public Integer poll() {
    if (tail.get() == head.get()) {
      System.out.println("队列已空");
      return false;
    }
    int index = (head.get() + 1) % atomicReferenceArray.length();
    Integer ele = atomicReferenceArray.get(index);
    if (ele == null) {
      return poll();
    }
    while (!atomicReferenceArray.compareAndSet(index,ele,EMPTY)) {
      return poll();
	}
    head.incrementAndGet();
    System.out.println("出对成功");
    return ele;
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无锁队列是一种线程安全的数据结构,可以在多线程环境下高效地进行数据交换。C11标准引入了原子变量,可以用来实现无锁队列无锁队列实现思路是利用原子变量的CAS操作(Compare-And-Swap)来实现队列的入队和出队操作。CAS操作是原子性的,可以保证在多线程环境下的正确性。 下面是一个使用原子变量实现无锁队列的代码示例: ```c #include <stdatomic.h> #define QUEUE_CAPACITY 100 typedef struct { atomic_int head; // 队头索引 atomic_int tail; // 队尾索引 int data[QUEUE_CAPACITY]; // 队列数据 } queue_t; // 初始化队列 void queue_init(queue_t *q) { atomic_init(&q->head, 0); atomic_init(&q->tail, 0); } // 入队操作 void queue_push(queue_t *q, int value) { int tail = atomic_load(&q->tail); int next_tail = (tail + 1) % QUEUE_CAPACITY; while (next_tail == atomic_load(&q->head)) { // 队列已满,等待空闲位置 } q->data[tail] = value; atomic_store(&q->tail, next_tail); } // 出队操作 int queue_pop(queue_t *q) { int head = atomic_load(&q->head); int next_head = (head + 1) % QUEUE_CAPACITY; while (head == atomic_load(&q->tail)) { // 队列为空,等待数据 } int value = q->data[head]; atomic_store(&q->head, next_head); return value; } ``` 在这个代码中,我们使用了atomic_int类型来定义队头和队尾的原子变量。入队操作中,我们使用while循环来等待队列中有空闲位置,然后使用CAS操作将数据存入队列。出队操作中,我们使用while循环来等待队列中有数据可取,然后使用CAS操作将数据取出队列。 需要注意的是,这个代码示例中没有考虑在多线程环境下的竞争问题,可能会出现ABA问题等问题。在实际应用中需要根据具体情况进行优化和改进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值