无锁队列(Lock-Free Queue)是一种并发数据结构,它允许多个线程同时进行入队和出队操作,而不需要使用传统的锁机制来保证线程安全。无锁队列通过使用原子操作(如CAS,Compare-And-Swap)来实现线程安全,从而避免了锁带来的性能瓶颈和死锁问题。
head
和 tail
,分别指向队列的头和尾。#include <atomic>
#include <memory>
template <typename T>
class LockFreeQueue {
private:
struct Node {
T data;
std::atomic<Node*> next;
Node(T const& data_) : data(data_), next(nullptr) {}
};
std::atomic<Node*> head;
std::atomic<Node*> tail;
public:
LockFreeQueue() : head(new Node(T())), tail(head.load()) {}
~LockFreeQueue() {
while (Node* const old_head = head.load()) {
head.store(old_head->next);
delete old_head;
}
}
void enqueue(T const& data) {
std::unique_ptr<Node> new_node(new Node(data));
Node* old_tail = tail.load();
while (!old_tail->next.compare_exchange_weak(nullptr, new_node.get())) {
old_tail = tail.load();
}
tail.compare_exchange_weak(old_tail, new_node.get());
new_node.release();
}
bool dequeue(T& result) {
Node* old_head = head.load();
while (old_head != tail.load() && !head.compare_exchange_weak(old_head, old_head->next.load())) {
old_head = head.load();
}
if (old_head == tail.load()) return false;
result = old_head->next.load()->data;
delete old_head;
return true;
}
};
通过以上方法,无锁队列能够在保证线程安全的同时,提供高效的并发性能。
领取专属 10元无门槛券
手把手带您无忧上云