无锁队列的环形数组实现(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论文集》
- 无锁队列的环形数组实现(Lock Free Queue Implementation in Ring Array)
- 多线程无锁(lock-free)队列(queue)的实现探讨
- 无锁队列 lock free queue
- 自扩充的无锁(Lock-Free)并发环形队列算法
- Yet another implementation of a lock-free circular array queue
- Yet another implementation of a lock-free circular array queue
- 无锁(lock-free)队列的一个简单实现
- 数据结构队列之环形队列的动态数组实现:queue
- 环形缓冲区(ring buffer),环形队列(ring queue) 原理
- 环形缓冲区(ring buffer),环形队列(ring queue) 原理
- 环形无锁队列的简易实现
- 并发无锁环形队列的实现
- 环形队列的数组实现
- 数组实现的 环形队列
- 多线程无锁(lock-free) 堆的实现
- 眉目传情之并发无锁环形队列的实现
- 基于kfifo的内核无锁(Lock-free)驱动的实现
- 无锁环形队列
- oj C++继承(改错题)
- java中 Random类的用法
- 【Leetcode】Sort List
- 鱼类小志
- SourceTree 添加远程仓库时报错
- 无锁队列的环形数组实现(Lock Free Queue Implementation in Ring Array)
- #include #import @class
- 我的算法学习之路
- dos中ren命令与通配符的使用
- C语言之指针、数组和函数
- 走!翻越这座山,遇见更好的自己
- rpath添加依赖库搜索路径
- c++随机数生成
- JAVA正则表达式