以原子方式减少联盟的数据成员?

时间:2015-11-04 20:47:04

标签: c++ multithreading atomic compare-and-swap

我在与uint64_t的联合中有一个结构,提供对两个int32_t的访问。我想原子地减少一个struct成员。我想出了这个:

class{

public:

void atomicallyDecrement_B(const int32_t decrementByThisValue){
    MyUnion newUnion;
    MyStruct currentStruct = _union._data;

    do{
        const int32_t currentB = currentStruct.b;
        const int32_t currentA = currentStruct.a;
        const int32_t newB = currentB - decrementByThisValue;

        newUnion._data.a = currentA;
        newUnion._data.b = newB;
    }
    while(!std::atomic_compare_exchange_weak(&_union._data, &currentStruct, newUnion._data));
}

private:
    struct MyStruct{
        int a;
        int b;
    };

    union MyUnion{
        MyUnion(){
            _data.a = 0;
            _data.b = 0;
        }

        MyStruct _data;
        uint64_t _atomic;
    } _union;
};

但似乎atomic_compare_exchange_weak()的第一个参数必须是原子类型本身。有没有办法执行此操作没有将uint64_t数据成员更改为std::atomic<uint64_t>

我正在使用GCC 5.2

2 个答案:

答案 0 :(得分:1)

是的,有办法做到这一点。您可以使用此处找到的GCC原子内置函数:https://gcc.gnu.org/onlinedocs/gcc-4.4.5/gcc/Atomic-Builtins.html,也可以使用操作系统提供的原子函数。第三种选择是使用原子汇编指令。

答案 1 :(得分:1)

GCC将内核操作作为内置函数。它们在this page上进行了描述。

您正在寻找的操作是

type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)

bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)

这些内置函数执行原子比较和交换。也就是说,如果* ptr的当前值是oldval,则将newval写入* ptr。

对于Windows用户,相应的功能是

LONG __cdecl InterlockedCompareExchange(
  _Inout_ LONG volatile *Destination,
  _In_    LONG          Exchange,
  _In_    LONG          Comparand
);

其中描述了here

使用gcc内在的bool形式的例子:

do{
   int oldVal = protectedVal;
   int newVal = someFunction(oldVal);
} while (__sync_bool_compare_and_swap(&protectedVal, oldVal, newVal);