Search code examples
c++multithreadingc++11stdatomic

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?


Solution

  • 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).