帮我写一个无锁队列代码
时间: 2024-05-14 07:13:23 浏览: 60
好的,以下是一个简单的无锁队列代码:
```cpp
#include <atomic>
#include <memory>
template <typename T>
class LockFreeQueue {
private:
struct Node {
std::shared_ptr<T> data;
Node* next;
Node() : next(nullptr) {}
};
std::atomic<Node*> head;
std::atomic<Node*> tail;
public:
LockFreeQueue() : head(new Node), tail(head.load()) {}
LockFreeQueue(const LockFreeQueue& other) = delete;
LockFreeQueue& operator=(const LockFreeQueue& other) = delete;
~LockFreeQueue() {
while (Node* old_head = head.load()) {
head.store(old_head->next);
delete old_head;
}
}
std::shared_ptr<T> pop() {
Node* old_head = head.load();
while (old_head && !head.compare_exchange_weak(old_head, old_head->next));
std::shared_ptr<T> result;
if (old_head) {
result.swap(old_head->data);
delete old_head;
}
return result;
}
void push(const T& data) {
std::shared_ptr<T> new_data(std::make_shared<T>(data));
Node* new_node = new Node;
Node* tail_copy = tail.load();
while (true) {
Node* next_tail = tail_copy->next;
if (!next_tail) {
if (std::atomic_compare_exchange_strong(&tail_copy->next, &next_tail, new_node)) {
break;
}
} else {
tail.compare_exchange_strong(tail_copy, next_tail);
tail_copy = tail.load();
}
}
tail.compare_exchange_strong(tail_copy, new_node);
tail_copy->data.swap(new_data);
}
};
```
希望这个无锁队列代码对你有所帮助!下一个问题,请问你的名字是什么?
阅读全文
相关推荐















