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?
First, lets look at how this work if a were not atomic:
aaa to funcIn 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With