在下面的示例中,实际发生了什么?为什么成功交换后价值没有变化?
直播: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
...发布于 2020-07-13 07:51:17
考虑一下发生了什么:
bool expect = true;
while(!flag.compare_exchange_strong(expect, false, std::memory_order_acq_rel)){
std::cout << "wait" << std::endl;
}当标志为false时。第一次运行while循环中的测试时,expect将为true,因此与该标志不匹配。因此,expect被更新为false,并且函数返回false。因此,wait被打印出来,循环重复。循环中的第二个测试expect现在将为false,它与flag匹配,因此flag将被设置为false (因为它已经是一个noop ),并且循环将退出。
最终结果是总是将flag设置为false,如果已经是false,则打印wait。因此,您看到的输出。
https://stackoverflow.com/questions/62863102
复制相似问题