Why does std::memory_order_acq_rel always trigger warnings in C++11?

86 views Asked by At

My compiler is clang 18.1.0-rc1; and the following code triggers two warnings:

#include <atomic>

std::atomic<int> n;

int main() {
    // Warning: Memory order argument to atomic operation is invalid
    n.load(std::memory_order_acq_rel); 

    // Warning: Memory order argument to atomic operation is invalid
    n.store(1, std::memory_order_acq_rel);
}

What's the legal usage of std::memory_order_acq_rel?


Update

n.fetch_add(1, std::memory_order_acq_rel); // now is ok
2

There are 2 answers

3
Peter Cordes On BEST ANSWER

It's valid with RMWs like fetch_add that both load and store in one operation.

The acquire part of acq_rel is valid for the load side, the release part is valid for the store side.

0
273K On

It warns you about undefined behaviors in your code.

std::atomic<T>::load: If order is one of std::memory_order_release and std::memory_order_acq_rel, the behavior is undefined.

std::atomic<T>::store: If order is one of std::memory_order_consume, std::memory_order_acquire and std::memory_order_acq_rel, the behavior is undefined.

The valid operations for std::memory_order_acq_rel are std::atomic<T>::fetch_add, std::atomic<T>::exchange() and the other read-modify-write operations.