【问题标题】:C++ simple threads exampleC++ 简单线程示例
【发布时间】:2016-03-23 21:12:37
【问题描述】:

您好,我正在学习 c++ 和线程。我是 c++ 新手,以下代码是我自己根据其他语言的经验编写的。但是,尽管对我来说它似乎没问题并且可以编译,但是当我执行它时,它挂起 - 什么都不做。你能告诉我我做错了什么吗?

#include <iostream>
#include <thread> 
#include <vector>
#include <string> 

void printLine(std::string str) {   
    std::cout << str << std::endl; 
}

void child(int id) {    
    printLine("This is a thread with id: " + std::to_string(id)); 
}

int main() {

    printLine("This is the main thread and we are baout to spawn threads...");      
    std::vector<std::thread> threads;

    for (int i = 0; i < 10; i++) {

        threads[i] = std::thread(child, i);         
        threads[i].join();

    }

    printLine("Press any key to exit...");  
    std::getchar();

    return 0;

}

【问题讨论】:

  • 越界访问所以未定义的行为:threads[i] = std::thread(child, i); 。向量threads 为空。
  • 当您不在 for 循环之外使用线程时,为什么要将线程“添加”到向量中?
  • 对于投反对票并认为这是一个愚蠢的问题的人,如果您至少可以提供有关我的错误而不是投反对票的参考,我将不胜感激。

标签: c++ multithreading


【解决方案1】:

你的代码试图让一些线程运行不是问题,它与测试用例有关:

std::vector<std::thread> threads;

for (int i = 0; i < 10; i++) {

    threads[i] = std::thread(child, i);         
    threads[i].join();

}

threads 在进入for 循环时为空,因此访问threads[0] 或> 0 会导致未定义行为。

您应该使用push_back(或emplace_back)来实际添加元素到vector

std::vector<std::thread> threads;

for (int i = 0; i < 10; i++) {

    threads.push_back(std::thread(child, i));         
    threads[i].join();
}

【讨论】:

  • @Juanchopanza 没错,我试图关注导致 UB 的部分,而不是代码的实际意义。
猜你喜欢
  • 2014-01-17
  • 1970-01-01
  • 2011-03-27
  • 2012-01-11
  • 2013-04-18
  • 1970-01-01
  • 2010-10-10
  • 2011-06-03
相关资源
最近更新 更多