I have a lambda inside a for loop with the loop variable parameter in the lambda. When I run it, I expect the numbers 0-9 to be output. But since it is a lambda, the x doesn't get evaluated immediately.
for (int x = 0; x < n; ++x)
{
vec.push_back(thread{[&x]() {
m.lock();
cout << x << endl;
m.unlock();
}});
}
Output:
0
3
3
9
etc.
The solution for other languages would be to create a temporary variable,
for (int x = 0; x < n; ++x)
{
int tmp = x;
vec.push_back(thread{[&tmp]() {
m.lock();
cout << tmp << endl;
m.unlock();
}});
}
but that doesn't seem to work.
see Threads receiving wrong parameters
Bonus:
In my search for an answer, I stumbled upon this question
Generalizing C++11 Threads class to work with lambda
which recommends not using a container that would invalidate the iterators.
Why would that be?