我是新来的C++多线程编程,并试图在我的代码中使用线程池。我的代码非常简单。池中的最大线程数
#include <iostream>
#include <vector>
#include <thread>
const int SIZE = 100000;
void foo() {
std::cout << "foo" << std::endl;
}
int main() {
std::vector<std::thread> myThreads;
for (int i = 0; i < SIZE; i++) {
myThreads.push_back(std::thread(foo));
}
for (auto& myThread : myThreads) {
myThread.join();
}
return 0;
}
当我从Windows 10上的Visual Studio 15运行此代码时,没有问题。有用。我的问题是,当我在我的树莓派3运行它,我得到一个错误,指出:
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
现在我认为发生的事情是,郫县的薄弱CPU根本无法在处理线程的这么大的量一旦。当我将SIZE更改为100或200时,代码执行得很好。
那么为什么这么多线程导致程序失败呢?线程是否等待被执行或者是什么问题?
可能重复执行不大于N(通常是
std::thread::hardware_concurrency()
) [多线程在C++中抛出线程构造tor失败:资源暂时不可用](http://stackoverflow.com/questions/26691340/multi-threading-in-c-throws-thread-constructor-failed-resource-temporarily-un) – Swift你错误地解释了线程池。池是少量线程,通常只有每个可用的处理器内核可用于执行工作。作业分配给池,其中一个线程将分配作业。有一些工作分配计划来分散工作,以便没有一个线程被过度纳税,而另一些线程闲置。 – user4581301
线程池的重点在于允许您使用少量的线程,而不是比您拥有的核心数量大得多。看看[this](http://stackoverflow.com/a/29742586/721269)我写的简单线程池。 –