为什么C++ 11 CAS操作需要两个指针参数?

Kno*_*abe 14 c++ compare-and-swap c++11

许多C++ 11 CAS操作(例如,的atomic_compare_exchange_weak,atomic_compare_exchange_strong)取两个指针和值,即,是这样的:

bool atomic_compare_exchange(T* pointer, T* expected,       // pseudodeclaration!
                             T desired);
Run Code Online (Sandbox Code Playgroud)

相比之下,来自Microsoft,gcc和Intel的CAS操作都采用一个指针和两个值:

long InterlockedCompareExchange(long* pointer, long desired,       // Microsoft
                                long expected);

int __sync_bool_compare_and_swap (T* pointer, T expected,          // gcc and
                                  T desired);                      // Intel
Run Code Online (Sandbox Code Playgroud)

为什么C++ 11 CAS函数需要两个指针和一个值,而不是看起来更传统的一个指针和两个值?

Ker*_* SB 22

在C++ 11的方式是比较有用的:如果交换失败,则*expected更新到新的当前值.这使得在循环中使用该函数变得容易:

T value = x.load();
T newvalue = frob(value);

while (!atomic_compare_exchange(&x, &value, newvalue))
{
    newvalue = frob(value);
}
Run Code Online (Sandbox Code Playgroud)

使用Microsoft签名,测试操作是否成功更加繁琐,并且与GCC __sync_type版本相同.使用GCC __sync_bool,您甚至需要在每次交换失败时执行另一次加载.