Mrd*_*sim -3 c++ multithreading
我在C++中进行多线程处理.我在Windows上.这就是我所拥有的:
int i;
try {
std::vector<std::thread> threads;
for (i = 0; i < threadscount; i++) {
threads.push_back(std::thread(myvoid));
std::cout << "started\n";
}
for (i = 0; i < threadscount; i++) {
threads[i].join();
std::cout << "joined\n";
}
}
catch (...) {}
Run Code Online (Sandbox Code Playgroud)
但是当我设置threadscount为2000个线程时,我得到:
已经调用了abort().
为什么会这样?我能解决这个问题吗?
似乎在Windows上,限制是堆栈空间.如果减少给予每个线程的堆栈空间量,则可以增加线程数.
参考这里:
https://blogs.msdn.microsoft.com/oldnewthing/20050729-14/?p=34773/
编辑:
刚刚在我的imac上敲了这个测试程序.在耗尽资源之前设法创建了2047个线程.你的旅费可能会改变 :-)
#include <iostream>
#include <thread>
#include <exception>
#include <stdexcept>
#include <vector>
void myvoid()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
}
void start_thread(std::vector<std::thread>& threads)
{
try
{
threads.push_back(std::thread(myvoid));
std::cout << "started " << threads.size() <<"\n";
}
catch(...) {
std::cout << "failed to start at " << threads.size() + 1 << "\n";
throw;
}
}
auto main() -> int
{
std::vector<std::thread> threads;
try {
for(;;)
start_thread(threads);
}
catch(...)
{
}
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
样本输出:
...
started 2042
started 2043
started 2044
started 2045
started 2046
started 2047
failed to start at 2048
$
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4480 次 |
| 最近记录: |