循环内的c ++线程打印错误的值 [英] c++ Threads inside for loop print wrong values

查看:52
本文介绍了循环内的c ++线程打印错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解 C++ 中的多线程,但我遇到了这个问题:如果我在 for 循环中启动线程,它们会打印错误的值.这是代码:

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;
}

我期望打印值 0、1、2、3、4,但我经常得到相同的值两次.这是输出:

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

我缺少什么?

推荐答案

[&] 语法导致 i通过引用捕获em>.因此,当线程运行时,i 通常会比您预期的更先进.更严重的是,如果 i 在线程运行之前超出范围,则您的代码的行为未定义.

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.

按值捕获 i - 即 std::thread([i](){ print_id(i); }) 是修复.

Capturing i by value - i.e. std::thread([i](){ print_id(i); }) is the fix.

这篇关于循环内的c ++线程打印错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆