以下是一个简单的C++无锁队列的实现示例,不使用C++11特性:
#include <atomic>
template<typename T>
class LockFreeQueue {
private:
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
std::atomic<Node*> head;
std::atomic<Node*> tail;
public:
LockFreeQueue() : head(nullptr), tail(nullptr) {}
void enqueue(const T& value) {
Node* newNode = new Node(value);
while (true) {
Node* last = tail.load();
Node* next = last->next;
if (last == tail.load()) { // Ensure no other thread has modified 'tail'
if (next == nullptr) { // 'last' is actually the last node
if (std::atomic_compare_exchange_strong(&last->next, &next, newNode)) {
std::atomic_compare_exchange_strong(&tail, &last, newNode);
return;
}
} else { // 'tail' was not pointing to the last node
std::atomic_compare_exchange_strong(&tail, &last, next);
}
}
}
}
bool dequeue(T& result) {
while (true) {
Node* first = head.load();
Node* last = tail.load();
Node* next = first->next;
if (first == head.load()) { // Ensure no other thread has modified 'head'
if (first == last) { // Queue is empty or being modified by another thread
if (next == nullptr)
return false; // Queue is empty
std::atomic_compare_exchange_strong(&tail, &last, next);
} else { // Read 'data' before CAS
result = next->data;
if (std::atomic_compare_exchange_strong(&head, &first, next)) {
delete first; // Safe to delete the old head node now
return true;
}
}
}
}
}
};
注意,此示例只提供了一个基本的无锁队列实现,并没有处理内存管理和线程同步的所有细节。实际使用时,请确保正确处理内存释放、ABA问题以及线程安全等方面的细节,并进行适当的测试和验证。
内容由零声教学AI助手提供,问题来源于学员提问




