I have 2 threads created using lambdas, Inside of lambda i am calling a my function where i am manipulating my global variables.
I believe when we don't pass values to functions inside thread with keyword std::ref(), it will passed by value even though function parameters are reference variables. But here in my program I expect x, y, z variables to print only 0, 0, 0 as I have not used std::ref to pass variables but it prints 9, 0, 0 sometime and 0, 0, 0 other time. Am i missing something here?
Please find my code below
I have tried executed below program to test my output
#include <stdio.h>
#include <iostream>
#include <thread>
using namespace std;
int x = 0;
int y = 0;
int z = 0;
void func(int& a, int& b)
{
for (int i = 0; i < 10000; ++i)
{
a += i;
b += i;
}
}
int main()
{
std::thread t1([]() {
func(x, z);
});
std::thread t2([]() {
func(y, z);
});
cout << "x,y,z=" << x << " " << y << " " << z << " " << endl;
t1.join();
t2.join();
getchar();
return 0;
}