c++ Threads inside for loop print wrong values

Ermando :

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 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 I'm missing?

Bathsheba :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29288&siteId=1