gpt4 book ai didi

C++11 无锁栈

转载 作者:行者123 更新时间:2023-12-04 14:12:52 27 4
gpt4 key购买 nike

我正在阅读 Anthony Williams 的 C++ Concurrency in Action,但不明白它的 push lock_free_stack 的实现类(class)。

为什么地球上的原子load不在while循环中?他给出的理由是:

You therefore don’t have to reload head each time through the loop, because the compiler does that for you.



但我看不懂图片。有人可以对此有所了解吗?
template<typename T>
class lock_free_stack
{
private:
struct node
{
T data;
node* next;
node(T const& data_) :
data(data_)
{}
};
std::atomic<node*> head;
public:
void push(T const& data)
{
node* const new_node=new node(data);
new_node->next=head.load();
while(!head.compare_exchange_weak(new_node->next,new_node));
}
};

最佳答案

关键在 compare_exchange_weak 的界面,在这种情况下需要 2 个参数。第一个是对期望值的引用,第二个是期望值。如果原子的当前值不等于预期输入,它将返回 false 并将预期输入设置为当前值。

所以在这种情况下,它所做的是设置 new_node->next = head .然后,它说如果 head仍然等于 new_node->next ,把它换成 head .如果它不再是那个值,它使用对 new_node->next 的引用。为其分配 head 的当前值.由于失败的循环的每次迭代也会替换 new_node->next当前值为 head , 没有读取来复制循环体中的内容。

关于C++11 无锁栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493829/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com