Reputation: 9
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;
}
Upvotes: 0
Views: 110
Reputation: 11178
You have a problem here. Two threads are writing to the same targets without protection (a mutex), so your results are undefined.
When two threads write to the same variable, unless the operation is atomic the result might not be what you expected.
Example:
int x = 0;
function 1: x++;
function 2: x++;
The result might be 1 instead of the expected 2 because the function 2 might read x as 0, before function 1 has modified it.
Also, you don't wait for the threads to finish as the comment says.
Good practises:
Upvotes: 1