我是新來的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)我寫的簡單線程池。 –