Aimin Huang
Aimin Huang

Reputation: 175

Understanding memory order relaxed in C++

std::atomic<int> unique_ids;

void foo() {    
  int i = unique_ids.fetch_add(1, std::memory_order_relaxed);
  std::cout<<i;
}

int main(int argc, char* argv[]) {
  std::vector<std::thread> threads;
  for (int i = 0; i < 9; ++i) {
       threads.emplace_back(foo);
  }

  for (int i = 0; i < 9; ++i) {
      threads[i].join();
  }
  std::cout << std::endl;
  return 0;
}

My aim is to use atomic to generate unique id for concurrency program but I do not care about the orders.

For the above code, my understanding is that the output values in foo should be different although their orders are not guaranteed.

I tested the above code hundred times and all the results are what I expected. I am a beginner of atomic / memory order, could anyone help me clarify my understanding?

Thanks in advance. Aimin

P.S. I would like to point out that this question is not the same as the one c++,std::atomic, what is std::memory_order and how to use them since my question is specifically about the understanding of memory_order_relaxed rather than a generic question about the explanation of atomic and memory order.

Upvotes: 7

Views: 1373

Answers (2)

Carlo Wood
Carlo Wood

Reputation: 6791

The specification of the memory order only has to do with other reads/writes by this thread that are done before and/or after this memory access, which are then read by other threads (aka, the order in which threads see the side effects of at least two accesses by another thread).

Since there is only a single memory access (per thread) involved here (albeit a read-modify-write access), the memory order is irrelevant and relaxed will work fine.

Note however that read-modify-write operations are special on top of this; those always have a total global order, independent of the memory order specified; meaning that every thread will see the side-effects (the value of the atomic) in the same order; none will first see 3 and then 2, even if they'd only be reading the value.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182743

This is a legitimate use of relaxed memory ordering. You just need the operation to be atomic with respect to other accesses to the very same atomic. Every atomic operation has that characteristic regardless of memory ordering or it wouldn't be atomic at all.

Upvotes: 3

Related Questions