帮我写一份无锁的queue
时间: 2023-10-31 20:09:43 浏览: 36
好的,这里给您提供一份使用 C++11 的无锁队列实现:
```c++
#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;
Node* pop_head() {
Node* old_head = head.load();
if (old_head == tail.load()) {
return nullptr;
}
head.store(old_head->next);
return old_head;
}
public:
LockFreeQueue() : head(new Node), tail(head.load()) {}
LockFreeQueue(const LockFreeQueue&) = delete;
LockFreeQueue& operator=(const LockFreeQueue&) = delete;
~LockFreeQueue() {
while (Node* old_head = head.load()) {
head.store(old_head->next);
delete old_head;
}
}
std::shared_ptr<T> pop() {
Node* old_head = pop_head();
if (!old_head) {
return std::shared_ptr<T>();
}
std::shared_ptr<T> const res(old_head->data);
delete old_head;
return res;
}
void push(T new_value) {
std::shared_ptr<T> new_data(std::make_shared<T>(std::move(new_value)));
Node* p = new Node;
Node* const old_tail = tail.load();
old_tail->data.swap(new_data);
old_tail->next = p;
tail.store(p);
}
};
```
这个无锁队列使用了 C++11 的原子变量来保证线程安全,同时使用了智能指针来管理内存,避免了手动申请和释放内存的麻烦。具体实现上,使用两个原子指针 head 和 tail 分别指向队列头和尾,push() 操作在队列尾插入元素,而 pop() 操作从队列头弹出元素。这里使用了一个哨兵节点来简化实现。