gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:35:02 27 4
gpt4 key购买 nike

许多 C++11 CAS 操作(例如,atomic_compare_exchange_weakatomic_compare_exchange_strong)采用两个指针和一个值,例如:

bool atomic_compare_exchange(T* pointer, T* expected,       // pseudodeclaration!
T desired);

相比之下,微软、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

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

最佳答案

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

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

while (!atomic_compare_exchange(&x, &value, newvalue))
{
newvalue = frob(value);
}

使用微软签名,测试操作是否成功比较麻烦,GCC的__sync_type版本也是如此。使用 GCC 的 __sync_bool,您甚至需要在每次交换失败时执行另一个加载。

关于c++ - 为什么 C++11 CAS 操作需要两个指针参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16043723/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com