I am currently trying to get a better understanding of multithreading and am experimenting using std::thread.
I have this piece of code:
volatile int m = 0;
void ThdFun(int i)
{
for (int j = 0; j < i; ++j) {
m++;
//std::cout << "hello1 " << m << " " <<std::endl;
}
//std::cout << "Hello World from thread " << i <<" " << std::endl;
}
int main(){
int var = 100000; //changes when i want to experiment with diff values
std::thread t1(ThdFun, var);
std::thread t2(ThdFun, var);
t1.join();
t2.join();
std::cout << "final result of m: " << m << std::endl;
if ((var * 2) == m) {
std::cout << "CORRECT" << std::endl;
}
else
std::cout << "INCORRECT" << std::endl;
return 0;
}
What I noticed is that if my var = 2
or var =50
, I get the correct output (which is 4 and 100 respectively)
But when I make var
a large number like 100000, I get anything in the range of 100000-200000, when I would expect to get 200000. I'm wondering why this happens, because to my understanding isn't the 'join()' function supposed to make it go in sequential order? Also why is the output fine for 'smaller' numbers but it gets unpredictable with larger numbers? Is 1 thread finishing and thus exiting the program or something?
Could someone please explain what is happening that causes this varying output for large numbers, and why the join() doesn't work well for larger numberss?
Thank you!