I\'m trying to understand Multi-threading in c++, but I\'am stuck in this problem: if I launch threads in a for loop they print wrong values. This is the code:
#
Two problems:
You have no control over when the thread runs, which means the value of the variable i
in the lambda might not be what you expect.
The variable i
is local for the loop and the loop only. If the loop finishes before one or more thread runs, those threads will have an invalid reference to a variable whose lifetime have ended.
You can solve both these problems very simply by capturing the variable i
by value instead of by reference. That means each thread will have a copy of the value, and that copy will be made uniquely for each thread.