0

I found a code below that is in some class.

std::atomic<bool> is_locked(false);
std::atomic<int> counter(0);

bool acquire(){
    counter.fetch_add(1,memory_order_acquire);
    if(is_locked.load(memory_order_acquire))
    { 
           return false;
    }
    return true;
}

I think "memory_order_acquire" is used with read operation. So I understand the function of load(memory_order_acquire).

However, fetch_add actually consists of two functions :

1) read current value

2) write new added value

There exists also a function that includes fetch_sub function to the "counter" with memory_order_release in this class.

What are the intention of memory_order_acquire in fetch_add and that of memory_order_release in fetch_sub ?? Couldn't it be possible to use memory_order_release in fetch_add instead??

mallea
  • 534
  • 6
  • 17
  • Possible duplicate of [C++11 memory\_order\_acquire and memory\_order\_release semantics?](http://stackoverflow.com/questions/16179938/c11-memory-order-acquire-and-memory-order-release-semantics) – tambre Feb 12 '17 at 08:52
  • Jeff Preshing has published a number of great articles on this. Here is [one](http://preshing.com/20120913/acquire-and-release-semantics) – LWimsey Feb 13 '17 at 00:37
  • A little more context could help – curiousguy Nov 26 '19 at 22:15

0 Answers0