无锁队列的环形数组实现(Lock Free Queue Implementation in Ring Array)

来源:互联网 发布:哪里能买到大数据 编辑:程序博客网 时间:2024/05/01 01:29

在网络服务器中,往往需要对数据进行高并发的读写操作。最原始的方式是对数据缓冲队列进行加锁(Mutex Lock),以完成的线程间的同步与互斥。但操作系统对资源进行加锁与解锁需要耗费很多时间,对于时间要求比较高或者要求迅速响应的服务器,锁的方式很有可能不能满足系统设计的要求。于是寻求设计一种不加锁也可以完成互斥访问的数据缓冲队列。

无锁队列的原理,首先可以参阅陈皓老师写的文章(http://coolshell.cn/articles/8239.html),其中有关于CAS等原子操作的介绍,使用链表的无锁队列的实现,以及可能面临的ABA问题。文中也给出了使用数组的的无锁队列的实现方案,但文中的方案只能存储一些较小的数据类型,如32位数据等。使用链表的无锁队列,元素每次入队和出队都涉及内存的申请和释放,内存IO的频繁操作不免要影响到系统效率。使用数组的无锁队列避免了内存的频繁操作,实现起来也清晰简洁。

Google的搜索结果中,无锁队列大部分都是基于链表的,数组形式的实现方案非常少。无锁队列的数组其实是一个环形数组(Ring Array),所有的入队和出队操作都是对该数组的内存进行操作。一个无锁队列的环形数组实现的C++定义如下:

class LockFreeQueue{public:LockFreeQueue(int s = MAX_SIZE_OF_RING_BUFFER);~LockFreeQueue();bool InitQueue(void);bool EnQueue(const ItemT & ele);bool DeQueue(ItemT * ele);//__sync_bool_compare_and_swaptemplate<class T>inline bool CAS (std::atomic<T> * reg, T old, T newVal){return std::atomic_compare_exchange_weak(reg,&old,newVal);}//__sync_fetch_and_addinline int FetchADD(std::atomic<int> * v, int add){return std::atomic_fetch_add(v,add) ;}//__sync_fetch_and_subinline int FetchSub(std::atomic<int> * v, int add){return std::atomic_fetch_sub(v,add) ;}private:ItemT * ring_array_;std::atomic<int> * flags_array_;//flags: 0:empty; 1:enqueue-ing; 2:enqueue-able; 3:dequeue-ing.int size_;std::atomic<int> item_num_;std::atomic<int> head_index_;std::atomic<int> tail_index_;};

由于代码还在改进和维护中,具体实现可以参考我放在GitHub上的文件,请移步:

https://github.com/xclyfe/libReactor/blob/master/Source/CMS/LockFreeQueue.h

https://github.com/xclyfe/libReactor/blob/master/Source/CMS/LockFreeQueue.cpp

参考文献:

1. 《Yet another implementation of a lock-free circular array queue》

2. 《Writing Lock-Free Code: A Corrected Queue》

3. 《用于并行计算的多线程数据结构,第 2 部分: 设计不使用互斥锁的并发数据结构》

4. 《Andrei Alexandrescu论文集》

5. 《Maged Michael论文集》

0 0
原创粉丝点击