C ++原子CAS(比较和交换)操作不会更改值 [英] C++ atomic CAS(compare-and-swap) operation does not change value
问题描述
在下面的示例中,实际发生了什么?成功交换后,为什么价值不会改变?
In the following example, what actually happens? Why value does not changes after successful exchange?
实时: https://wandbox.org/permlink/f5VYSKfQ9UJqa8FQ
std::atomic<bool> flag{false};
int main()
{
std::thread thread([](){
while(true){
// wait until flag not becomes true
{
bool expect = true;
while(!flag.compare_exchange_strong(expect, false, std::memory_order_acq_rel)){
std::cout << "wait" << std::endl;
}
}
std::cout << "work" << std::endl;
}
});
flag.store(true, std::memory_order_release);
thread.join();
}
输出:
work
wait
work
wait
...
推荐答案
考虑会发生什么:
bool expect = true;
while(!flag.compare_exchange_strong(expect, false, std::memory_order_acq_rel)){
std::cout << "wait" << std::endl;
}
当标志为假时.在while循环中第一次运行测试时, expect
将为true,因此与该标志不匹配.因此,将 expect
更新为false,并且该函数返回false.因此,将打印 wait
,然后重复循环.循环中的第二个测试 expect
现在将为false,与 flag
匹配,因此 flag
将设置为false(因为已经是),循环将退出.
when the flag is false. The first time the test in the while loop runs, expect
will be true, so does not match the flag. So expect
is updated to the false, and the function returns false. So wait
is printed and the loop repeats.
The second test in the loop, expect
will now be false, which matches flag
, so flag
will be set to false (a noop as it already is), and the loop will exit.
最终效果是始终将 flag
设置为false,并在 wait
已经存在的情况下打印 wait
.因此,您看到的输出.
The net effect will be to always set flag
to false, and print wait
if it was already false
. Thus, the output you see.
这篇关于C ++原子CAS(比较和交换)操作不会更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!