c++ Threads inside for loop print wrong values

后端 未结 3 1585
死守一世寂寞
死守一世寂寞 2021-02-18 18:32

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:

#         


        
3条回答
  •  甜味超标
    2021-02-18 19:21

    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.

提交回复
热议问题