C++中实现无锁队列可以使用原子操作和内存屏障等技术,以下是一个简单的示例代码:
#include <atomic>
template<typename T>
class LockFreeQueue {
private:
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
alignas(64) std::atomic<Node*> head;
alignas(64) std::atomic<Node*> tail;
public:
LockFreeQueue() : head(new Node(T())), tail(head.load()) {}
~LockFreeQueue() {
while (Node* node = head.load()) {
head.store(node->next);
delete node;
}
}
void Enqueue(const T& value) {
Node* newNode = new Node(value);
newNode->next = nullptr;
Node* curTail = tail.load();
Node* nullPtr = nullptr;
while (!tail.compare_exchange_weak(curTail, newNode)) {
curTail = tail.load();
if (curTail == nullPtr)
nullPtr = nullptr;
}
if (nullPtr != nullptr)
delete nullPtr;
// 在此处添加适当的内存屏障,例如 std::atomic_thread_fence(std::memory_order_release);
}
bool Dequeue(T& result) {
Node* curHead = head.load();
Node* curTail = tail.load();
// 检查队列是否为空
if (curHead == curTail)
return false;
Node* nextNode = curHead->next;
result = nextNode->data;
head.store(nextNode);
delete curHead;
// 在此处添加适当的内存屏障,例如 std::atomic_thread_fence(std::memory_order_release);
return true;
}
};
这是一个简单的无锁队列实现,使用了原子操作和适当的内存屏障来保证线程安全。请注意,在实际应用中,还需要考虑内存回收、并发控制等问题,并根据具体情况进行优化和测试。
内容由零声教学AI助手提供,问题来源于学员提问