相关疑难解决方法(0)

理解C++ 11中的std :: atomic :: compare_exchange_weak()

bool compare_exchange_weak (T& expected, T val, ..);
Run Code Online (Sandbox Code Playgroud)

compare_exchange_weak()是C++ 11中提供的比较交换原语之一.它在某种意义上很弱,即使对象的值等于它也会返回false expected.这是由于某些平台上的虚假故障导致一系列指令(而不是x86上的指令)用于实现它.在这样的平台上,上下文切换,由另一个线程重新加载相同的地址(或高速缓存行)等可能使原语失败.这是spurious因为它不是expected操作失败的对象(不等于)的值.相反,这是一种时间问题.

但让我感到困惑的是C++ 11标准(ISO/IEC 14882)中所说的,

29.6.5 ..虚假失败的后果是几乎所有弱比较和交换的使用都将处于循环中.

为什么几乎所有用途都必须处于循环中?这是否意味着我们会因为虚假失败而失败?如果是这样的话,为什么我们compare_exchange_weak()自己打扰使用并编写循环?我们可以使用compare_exchange_strong()我认为应该摆脱我们的虚假失败.有哪些常见用例compare_exchange_weak()

另一个问题有关.安东尼在他的书"C++ Concurrency In Action"中说,

//Because compare_exchange_weak() can fail spuriously, it must typically
//be used in a loop:

bool expected=false;
extern atomic<bool> b; // set somewhere else
while(!b.compare_exchange_weak(expected,true) && !expected);

//In this case, you keep looping as long as expected is still false,
//indicating that the compare_exchange_weak() …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading atomic c++11

77
推荐指数
4
解决办法
2万
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

multithreading ×1