I'm a beginner in CPP and we have reached in class the subject of threading. I'm trying to play with it a bit and it seem not to work as I want it.
I want each thread to push the number of j inside the vector and then print the vector to the console.
It seems that all of them print the value '10' the last value that j holds after the end of the loop.
vector<int> foo(int x) {
vector<int> a;
a.push_back(x);
return a;
}
void print(vector<int> vec) {
for (int i = 0; i<int(vec.size()); i++)
cout << vec[i] <<endl;
}
void foo2(int x) {
vector<int> b;
thread thr([&] {b = foo(x); });
thr.join();
mtx1.lock();
print(b);
mtx1.unlock();
}
int main() {
vector<thread> th;
for (int j = 0; j < 10; j++)
th.emplace_back(([&] {foo2(j); }));
for (int j = 0; j < 10; j++)
th[j].join();
}
NOTE: I want that the vector of threads will go inside the function call a new thread that will push the number into the vector and then print.
The output I get is:
10
10
10
10
10
10
10
10
10
10
I'm aiming for:
0
1
2
3
4
5
6
7
8
9
Thanks for your help.