参考博客:C++内存模型
compare_exchange_weak基本使用
bool compare_exchange_weak( T& expected, T desired,std::memory_order success,std::memory_order failure );
expected
:期望的值desired
想要写入的值
如果obj
和期望的值相同,则写入desired
并且返回true,否则将obj值写入expected
并返回fasle。此处不考虑伪失败的可能性。
// 场景一:failed std::atomic_int aival = 10;int expect_val = 20;bool bc = aival.compare_exchange_strong(expect_val, 30);// bc:false expect_val:10 aival=10//场景二:successaival = 10;expect_val = 10;bc = aival.compare_exchange_strong(expect_val, 30);// bc:true expect_val:10 aival=30//场景三:failed,伪失败,某些机器缺少compare-and-exchange原子指令//导致该操作执行一半的时候被别的线程打断,此时expect_val不会被更改aival = 10;expect_val = 10;bc = aival.compare_exchange_strong(expect_val, 30);// bc:false expect_val:10 aival=10
compare_exchange_weak和compare_exchange_strong的区别
compare_exchange_weak可能存在伪失败
的情况。即虽然对象值和expected
一致,但是在更新至desired
的过程中,行为被打断,导致返回false。
compare_exchange_strong不存在伪失败
的情况。只要对象值和expected
一致即返回true。即使更新失败,