I'm trying to understand multithreading in C++, but I’m 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 the values 0,1,2,3,4 but I often got the same value twice. This is the output:
Hello from thread 2
Hello from thread 3
Hello from thread 3
Hello from thread 4
Hello from thread 5
What am I missing?
i
by value to lambda,[i]
.emplace_back
is odd:emplace_back
takes a list of arguments and passes that on to a constructor forstd::thread
. You've passed a (rvalue) instance ofstd::thread
, hence will construct a thread, then move that thread into the vector. That operation is better expressed by the more common methodpush_back
. It'd be more sensible to either writethreads.emplace_back([i](){ print_id(i); });
(construct in place) orthreads.push_back(std::thread([i](){ print_id(i); }));
(construct + move) which are somewhat more idiomatic.