Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ threads inside a 'for' loop print wrong values

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?

like image 471
Ermando Avatar asked Feb 06 '20 10:02

Ermando


1 Answers

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.

like image 143
Bathsheba Avatar answered Sep 20 '22 19:09

Bathsheba