Search code examples
c++multithreadingmemory-modelstdatomic

Acquire-release memory order between multiple threads


Code:

std::atomic<int> done = 0;
int a = 10;

void f1() {
  a = 20;
  done.store(1, std::memory_order_release);
}

void f2() {
  if(done.load(std::memory_order_acquired) == 1) {
    assert(a == 20);
  }
}

void f3() {
  if(done.load(std::memory_order_acquired) == 1) {
    assert(a == 20);
  }
}

int main() {
  std::thread t1(f1);
  std::thread t2(f2);
  std::thread t3(f3);
  t1.join();
  t2.join();
  t3.join();
}

The question is if thread 2 & 3 both see done == 1, will the assertion a == 20 hold in both threads ? I know acquire-release works for a pair of threads. But does it work in multiple threads as well?


Solution

  • Yes. The release-acquire relationship holds separately for all pairs of threads (that access the same atomic location!) and guarantees that all writes (that appear in program order) before the release are visible to all reads (that appear in program order) after whichever corresponding acquire.