简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM