c++ Threads inside for loop print wrong values
问题 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: #include <iostream> #include <list> #include <thread> void print_id(int id){ printf("Hello from thread %d\n", id); } int main() { int n=5; std::list<std::thread> threads={}; for(int i=0; i<n; i++ ){ threads.emplace_back(std::thread([&](){ print_id(i); })); } for(auto& t: threads){ t.join(); } return 0; } I was expecting to get printed