已经调用了C ++ abort

时间:2015-12-11 14:17:30

标签: 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 (...) {} 

但是当我将threadscount设置为2000个线程时,我得到了:

  

已经调用了abort()。

为什么会这样?我可以找到解决方案吗?

3 个答案:

答案 0 :(得分:5)

似乎在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;
}

示例输出:

...
started 2042
started 2043
started 2044
started 2045
started 2046
started 2047
failed to start at 2048
$

答案 1 :(得分:0)

因为没有人能够期望能够启动2000个线程。您的计算机没有此资源。

有一个简单的解决方案 - 使用一个合理的线程数。提示 - 任何超过50的东西都可能是疯了,除非你有一个非常特殊的情况。

答案 2 :(得分:0)

如果系统在尝试创建所有这些线程时资源不足,那么这一行可能会引发异常:

        threads.push_back(std::thread(myvoid));

这会破坏向量threads,然后会调用std::terminate(),因为它会销毁可加入的std::thread

通过在threads块之前移动try的声明,然后确保加入(或分离)catch处理程序中的所有线程,可以使代码安全。

相关问题