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:
#
The [&]
syntax is causing i
to be captured by reference. So quite often therefore i
will be further advanced when the thread runs than you might expect. More seriously, the behaviour of your code is undefined if i
goes out of scope before a thread runs.
Capturing i
by value - i.e. std::thread([i](){ print_id(i); })
is the fix.