无锁队列通过原子操作和CAS实现多线程安全,避免互斥锁开销。核心是使用std::atomic与compare_exchange_weak/strong保证指针更新的原子性,典型结构包括SPSC数组队列和Michael & Scott链表算法。关键挑战为ABA问题与内存回收,需用版本号或Hazard Pointer等机制解决。

实现一个无锁队列(Lock-Free Queue)的关键在于利用原子操作(atomic operations)和内存顺序(memory ordering)来避免使用互斥锁,从而提升多线程环境下的性能。C++ 中可以通过 std::atomic 和 CAS(Compare-And-Swap)操作来实现。
无锁队列的核心是使用原子操作来安全地修改共享数据结构,而不需要加锁。最常用的操作是 compare_exchange_weak 或 compare_exchange_strong,它们能比较并交换指针值,保证在多线程竞争时只有一个线程能成功更新。
一个典型的无锁队列基于链表结构,包含头指针(head)和尾指针(tail),所有操作都通过原子方式更新这两个指针。
主要挑战包括:
立即学习“C++免费学习笔记(深入)”;
在特定场景下(如 SPSC),可以简化实现。以下是一个基于循环数组的 SPSC 无锁队列示例:
template<typename T, size_t Size>
class LockFreeQueueSPSC {
T buffer[Size];
std::atomic<size_t> head{0}; // 入队位置
std::atomic<size_t> tail{0}; // 出队位置
<p>public:
bool enqueue(const T& value) {
size_t current_tail = tail.load();
size_t next_tail = (current_tail + 1) % Size;
if (next_tail == head.load()) {
return false; // 队列满
}
buffer[current_tail] = value;
tail.store(next_tail);
return true;
}</p><pre class='brush:php;toolbar:false;'>bool dequeue(T& result) {
size_t current_head = head.load();
if (current_head == tail.load()) {
return false; // 队列空
}
result = buffer[current_head];
size_t next_head = (current_head + 1) % Size;
head.store(next_head);
return true;
}};
这个版本适用于单生产者单消费者场景,无需强内存序,性能高。但 SMP(多生产者多消费者)场景需要更复杂的设计。
这是经典的无锁队列算法,使用链表结构,每个节点包含数据和指向下一个节点的指针。
template<typename T>
class LockFreeQueueMPSC {
struct Node {
T data;
std::atomic<Node*> next;
<pre class='brush:php;toolbar:false;'>Node() : next(nullptr) {}
Node(const T& d) : data(d), next(nullptr) {}};
std::atomic<Node*> head; std::atomic<Node*> tail;
public: LockFreeQueueMPSC() { Node* dummy = new Node(); head.store(dummy); tail.store(dummy); }
void enqueue(const T& data) {
Node* new_node = new Node(data);
Node* old_tail = nullptr;
Node* old_next = nullptr;
while (true) {
old_tail = tail.load();
old_next = old_tail->next.load();
if (old_tail == tail.load()) { // 检查是否被其他线程修改
if (old_next == nullptr) {
if (old_tail->next.compare_exchange_weak(old_next, new_node)) {
tail.compare_exchange_weak(old_tail, new_node);
return;
}
} else {
// 队尾未更新,推进 tail
tail.compare_exchange_weak(old_tail, old_next);
}
}
}
}
bool dequeue(T& result) {
Node* old_head = nullptr;
Node* old_tail = nullptr;
Node* old_next = nullptr;
while (true) {
old_head = head.load();
old_tail = tail.load();
old_next = old_head->next.load();
if (old_head == head.load()) {
if (old_head == old_tail) {
if (old_next == nullptr) {
return false; // 队列为空
}
// tail 落后,尝试推进
tail.compare_exchange_weak(old_tail, old_next);
} else {
result = old_next->data;
if (head.compare_exchange_weak(old_head, old_next)) {
delete old_head; // 注意:此处有内存回收风险
return true;
}
}
}
}
}};
该实现遵循 Michael & Scott 算法逻辑,但在真实环境中需处理内存回收问题。直接 delete 节点可能导致其他线程访问已释放内存。
无锁队列虽然高效,但实现复杂,需注意以下几点:
memory_order_seq_cst 最安全,但可依据场景调整为 memory_order_acquire/release 提升性能。struct { Node* ptr; int version; }),配合 128 位 CAS(如有硬件支持)。基本上就这些。无锁队列适合对延迟敏感、锁竞争激烈的场景,但开发难度大,建议优先考虑成熟的库如 absl::Mutex、folly::MPMCQueue 或 boost::lockfree::queue。
以上就是c++++怎么实现一个无锁队列_c++无锁队列(lock-free queue)的实现原理的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号