【发布时间】: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