class LockFreeStack
{
using T = int;
private:
struct Node
{
T val;
Node *next;
};
public:
LockFreeStack() : head(nullptr), length(0){};
void Push(const T &val)
{
Node *new_node = new Node{val, nullptr};
Node *old_head = nullptr;
do
{
old_head = head.load(std::memory_order_release);
} while (!head.compare_exchange_strong(old_head, new_node, std::memory_order_acquire, std::memory_order_acquire));
new_node->next = old_head;
length.fetch_add(1, std::memory_order_relaxed);
}
};
但是和书上不一致:
class lock_free_stack
{
private:
struct node
{
std::shared_ptr data;
node* next;
node(T const& data_):
data(std::make_shared(data_))
{}
};
std::atomic head;
public:
void push(T const& data)
{
node* const new_node=new node(data); // 1
new_node->next=head.load(); //2
while(!head.compare_exchange_weak(new_node->next,new_node)); //3
}
};
我就很疑惑,他算法中一个线程 A 如果执行到 @2 被休眠,如果其他 push 线程 直接执行 @2 ,@3 ,修改了 head atomic 值,线程 A 不就一直卡死了吗?