Oleksiy
Oleksiy

Reputation: 39800

Why does this produce correct output?

I was just working on a multithreading/concurrency tutorial, and the following code (I think) is supposed to not work correctly, because 5 different threads operate on the same object.

But it prints out exactly 500 every time. How does that work? I'm not using mutexes, so there is no protection against accessing the same data by multiple threads...

#include <iostream>
#include <vector>
#include <thread>
using namespace std;

struct Counter {

    int value;

    void increment() {
        value++;
    }
};

int main(){

    Counter counter;
    counter.value = 0;

    vector <thread> threads;

    for (int i = 0; i < 5; i++){
        threads.push_back(thread([&counter](){
            for (int i = 0; i < 100; ++i){
                counter.increment();
            }
        }));
    }


    for (auto& thread : threads)
        thread.join();

    cout << counter.value << endl;

    cin.get();
    return 0;
}

Upvotes: 2

Views: 127

Answers (2)

Bungalo Soldier
Bungalo Soldier

Reputation: 154

Multi-Threaded processing can be a strange beast as Snps said, i think you add a few print statements to your so you can detect how it is behaving while its running. I normally do that when i run into something confusing with any thing threaded.

Upvotes: 1

Felix Glas
Felix Glas

Reputation: 15524

Depending on the compiler, the increment ++i will result in a single instruction, which means that the increment will likely be performed atomically.

However, execution still results in a data race when multiple threads write to the same memory without any form of synchronization and will lead to undefined behaviour. UB means that just about anything can happen, including showing the correct answer.

Upvotes: 3

Related Questions