我在 Visual studio 2015 中运行以下命令时遇到问题。
#include <thread>
#include <vector>
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10000; i++) {
cout << "Loop: " << i << endl;
vector<thread> threads;
for (int j = 0; j < 8; j++) {
try {
threads.push_back(thread([]() {int a = 4; a++; }));
}
catch (const system_error &se) {
cout << se.what() << endl;
exit(1);
}
}
for (int j = 0; j < 8; j++) {
threads.at(j).join();
}
}
return 0;
}
运行数千个循环后,程序捕获系统错误并输出:
...
3994
3995
3996
3997
3998
resource unavailable try again: resource unavailable try again
我知道可以同时运行的线程有最大数量,但在这种情况下,只有 8 个同时运行,之后它们就会被销毁。可以创建的总数是否有上限?
我尝试在 Linux 上使用 g++ 运行上面的代码,它运行良好,只有在 Windows(Visual Studio 和 mingw)上才会出现错误。有什么帮助吗? 谢谢。
最佳答案
通过了解如何在 Windows 上创建线程来最好地描述这里发生的情况。
每个线程在创建时都会被赋予一个 default 1Mb stack size 。您会注意到大约有 3998 个线程,这对应于大约 3.9Gb 的已用用户地址空间。这并非偶然,因为这对应于 64 位 Windows 下 32 位进程可用的大部分完整 4Gb 用户地址空间(内核空间为 64 位)。额外的空间是加载可执行文件和必要的系统 DLL 的地方。
通过将构建更改为 64 位,您已经大幅扩展了该地址空间。拥有 10000 个线程和 1Mb 堆栈只是九牛一毛,limiter becomes non-pagable kernel memory尽管 1Mb 堆栈可以并且将会被调出,导致系统速度慢得像爬行一样。
关于C++ 在循环中创建线程时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315723/