anekix anekix - 2 months ago 22
C++ Question

c++ threads race condition simulation

Here is a c++ program that runs

10
times with
5
different threads and each thread increments the
value
of
counter
so the final output should be
500
, which is exactly what the program is giving output. But i cant understand why is it giving
500
every time the output should be different as the increment operation is not
atomic
and there are no locks used so the program should give out different outputs in each case.

edit to increase probability of race condition i increased the loop count but still couldn't see any varying output

#include<iostream>
#include<thread>
#include<vector>

struct Counter {
int value;

Counter() : value(0){}

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

int main(){
int n = 50000;
while(n--){
Counter counter;

std::vector<std::thread> threads;
for(int i = 0; i < 5; ++i){
threads.push_back(std::thread([&counter](){
for(int i = 0; i < 1000; ++i){
counter.increment();
}
}));
}

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

std::cout << counter.value << std::endl;
}
return 0;
}

Answer

You're just lucky :)

Compiling with clang++ my output is not always 500:

500
425
470
500
500
500
500
500
432
440