Quick Q: Are "++a" and "a = a.load() + 1" equivalent if 'a' is "atomic<int>"?--StackOverflow

Quick A: No. Between a.load() and the addition and store to a is a window in which other threads can change the value of a, causing updates to be lost.

Recently on SO:

c++ atomic read/write misunderstanding

Why program with this code sometimes prints "2"?

int main() {
    std::atomic<int> a;
    a = 0;

    std::thread t1([&]{++a;});
    std::thread t2([&]{a++;});
    std::thread t3([&]{
        a = a.load() + 1;
    });

    t1.join();
    t2.join();
    t3.join();

    if (a != 3) {
        std::cout << "a: " << a << std::endl;
    }
}

I've thought std::atomic guarantees that all operations will be done atomically so writing here(incrementing) will use a memory barrier and we will have always "3" at the end of threads work. I've explored the code and found out that the problem thread is t3 but I can't understand why it is wrong.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.