Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does std::atomic<> post-increment take place?

I'm confused about how does the atomic post-increment actually work. For example

std::atomic<int> a = 1; // global
void func(int i) {
    std::cout << i;
}

// execute the following in two threads
func(a++);

I believe a finally becomes 3, but is it possible to see the output "11"? Is it safe to expect one of the two threads will definitely see a became 2?

like image 514
GuLearn Avatar asked Oct 26 '25 02:10

GuLearn


1 Answers

First, lets look at how this work if a were not atomic:

  1. Make a copy of a
  2. Increment a
  3. Pass the copy of a to func

In the atomic case, it is similar except that the copy/increment happens atomically. The copy is still passed to func.

Since the increment/copy is atomic, the first thread to call ++ will increment it from 1 to 2, and pass 1 to func. The second one will increment it from 2 to 3, and pass 2 to func. Note, the order of the calls to func is not deterministic, but it should be called once with the value 1, and once with the value 2.

Post-increment operator++ is defined to be equivalent to .fetch_add(1).

like image 101
Dave S Avatar answered Oct 27 '25 17:10

Dave S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!