这个队列中使用了Node结构体来表示队列中的节点,如果不想使用Node结构体,可以考虑使用std::atomicstd::shared_ptr<T>来代替。具体实现如下:
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <thread>
template <typename T>
class LockFreeQueue
{
public:
LockFreeQueue() : head_(std::make_shared<Node>()), tail_(head_.load()) {}
~LockFreeQueue()
{
while (std::shared_ptr<Node> old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed))
{
head_ = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
}
}
void push(const T &value)
{
auto new_node = std::make_shared<Node>(value);
auto tail = std::atomic_load_explicit(&tail_, std::memory_order_relaxed);
std::atomic_store_explicit(&tail->next_, new_node, std::memory_order_release);
std::atomic_store_explicit(&tail_, new_node, std::memory_order_release);
size_.fetch_add(1, std::memory_order_release);
}
bool try_pop(T &value)
{
auto const old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed);
auto const new_head = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
if (!new_head)
{
return false;
}
value = new_head->value_;
std::atomic_store_explicit(&head_, new_head, std::memory_order_release);
size_.fetch_sub(1, std::memory_order_release);
return true;
}
bool empty() const
{
return std::atomic_load_explicit(&size_, std::memory_order_acquire) == 0;
}
private:
struct Node
{
T value_;
std::shared_ptr<Node> next_;
Node() : next_(nullptr) {}
explicit Node(const T &value) : value_(value), next_(nullptr) {}
};
std::shared_ptr<Node> head_;
std::shared_ptr<Node> tail_;
std::atomic<size_t> size_{0};
std::condition_variable cv_;
};