为什么C ++ 11 CAS操作需要两个指针参数? [英] Why do C++11 CAS operations take two pointer parameters?
问题描述
许多C ++ 11 CAS操作(例如 atomic_compare_exchange_weak
, atomic_compare_exchange_strong
)采用两个指针,并且值,即像这样:
Many of the C++11 CAS operations (e.g., atomic_compare_exchange_weak
, atomic_compare_exchange_strong
) take two pointers and a value, i.e., like this:
bool atomic_compare_exchange(T* pointer, T* expected, // pseudodeclaration!
T desired);
相比之下,Microsoft,gcc和Intel的CAS操作都采用一个指针和两个值:
In contrast, the CAS operations from Microsoft, gcc, and Intel all take one pointer and two values:
long InterlockedCompareExchange(long* pointer, long desired, // Microsoft
long expected);
int __sync_bool_compare_and_swap (T* pointer, T expected, // gcc and
T desired); // Intel
为什么C ++ 11 CAS函数需要两个指针和一个值而不是似乎是更常规的一个指针和两个值?
Why do the C++11 CAS functions take two pointers and a value instead of what appears to be a more conventional one pointer and two values?
推荐答案
C ++ 11方式更有用:如果交换失败,然后更新 * expected
到新的当前值。这样可以很容易地在循环中使用该函数:
The C++11 way is more useful: If the exchange fails, then *expected
is updated to the new, current value. That makes it easy to use the function in a loop:
T value = x.load();
T newvalue = frob(value);
while (!atomic_compare_exchange(&x, &value, newvalue))
{
newvalue = frob(value);
}
使用Microsoft签名,测试操作是否成功比较麻烦,并且同上适用于GCC的 __ sync_type
版本。使用GCC的 __ sync_bool
,即使每次交换失败,您甚至都需要执行另一次加载。
With the Microsoft signature, testing whether the operation succeeded is more cumbersome, and ditto for GCC's __sync_type
version. With GCC's __sync_bool
, you even need to perform another load each time the exchange fails.
这篇关于为什么C ++ 11 CAS操作需要两个指针参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!