C++项目中实现无锁队列
C++中实现无锁队列(Lock-Free Queue)需要结合原子操作(如CAS)和内存模型,确保多线程环境下的线程安全。
一、基于链表的无锁队列实现
1. 数据结构设计
-
节点结构:每个节点包含数据和原子指针
next,用于链式连接。 -
头尾指针:使用
std::atomic<Node*>类型的head和tail,初始化时指向哑节点(Dummy Node)。
template<typename T>
class LockFreeQueue {
private:struct Node {T data;std::atomic<Node*> next;Node(const T& val) : data(val), next(nullptr) {}};std::atomic<Node*> head;std::atomic<Node*> tail;public:LockFreeQueue() {Node* dummy = new Node(T()); // 哑节点head.store(dummy);tail.store(dummy);}~LockFreeQueue() {while (Node* old_head = head.load()) {head.store(old_head->next);delete old_head;}}
};
2. 入队操作(Push)
-
CAS更新尾指针:创建新节点后,通过
compare_exchange_weak原子更新tail指针。若失败(其他线程已修改tail),则重试。
void enqueue(const T& val) {Node* new_node = new Node(val);Node* old_tail = tail.load();while (!old_tail->next.compare_exc