Search code examples
c++multithreadingstdatomiccompare-and-swap

how can i call compare_exchange_weak(0,1) for an atomic variable in an array?


When I write down the code like this:

#include <atomic>
#include <array>
using namespace std;

int main() {
  array< atomic<int>, 5> a;
  a[1].compare_exchange_weak(0,1);
}

the compiler output:

no known conversion for argument 1 from 'int' to  'std::__atomic_base<int>::__int_type& {aka int &}'

So, can anyone explain why this failed? how can i use compare_exchange_weak in an atomic array?


Solution

  • The array part is irrelevant, compare_exchange_weak takes a reference as the first argument (the expected value). The literal 0 cannot be bound to a reference.

    You just need a local variable:

    int expected = 0;
    a[1].compare_exchange_weak(expected, 1);
    

    This is because, if the actual value differs, compare_exchange_weak sets the expected value to the actual value.