首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >terminate调用递归c++多线程

terminate调用递归c++多线程
EN

Stack Overflow用户
提问于 2020-07-21 16:51:35
回答 2查看 309关注 0票数 2

我是线程编程的新手,我面临着让我困惑的情况,我试图在我放在线程中的函数内部抛出异常,在main()函数中我有一个try and catch块,但是我仍然得到这些错误:

1. terminate called after throwing an instance of 'char const*'

2. terminate called recursively

下面是我的代码

代码语言:javascript
运行
复制
mutex m;

void AccumulateRange(uint64_t &sum, uint64_t start, uint64_t end) {
    for (uint64_t i = start;i<end;++i){
        sum+=i;
        if (sum>10) 
            throw "Number Exceed";
    }
}

int main(){

    const uint64_t num_threads = 1000;
    uint64_t nums = 1000*1000*1000;
    vector<uint64_t> v(num_threads);
    vector<thread> threads;
    uint64_t steps = nums/num_threads;

    for (uint64_t i = 0;i<num_threads;++i){
        try{
            threads.push_back(thread(AccumulateRange,ref(v[i]),steps*i,(i+1)*steps));
        }
        catch (const char& exception){
            cout<<exception<<endl;
        }
    }
    for (auto &t : threads){
        if (t.joinable())
           t.join();    
    }
    uint64_t total = accumulate(begin(v),end(v),0);
    return 0;
}

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-21 17:29:55

关于@DeltA的详细说明:您可以使用std::future,而不是使用std::thread并通过指针传递异常,因为它将抛出的异常存储在其共享状态中:

代码语言:javascript
运行
复制
void AccumulateRange(uint64_t& sum, uint64_t start, uint64_t end)
{
    for (uint64_t i = start; i < end; ++i)
    {
        sum += i;
        if (sum > 10)
            throw std::runtime_error("Number Exceed");
    }
}

int main()
{
    const uint64_t num_threads = 1000;
    uint64_t nums = 1000 * 1000 * 1000;
    std::vector<uint64_t> v(num_threads);
    std::vector<std::future<void>> futures;
    uint64_t steps = nums / num_threads;
    for (uint64_t i = 0; i < num_threads; ++i)
    {
        futures.push_back(std::async(std::launch::async, AccumulateRange, std::ref(v[i]), steps * i, (i + 1) * steps));
    }
    for (auto& f : futures)
    {
        try
        {
            f.get();
        }
        catch (const std::exception& e)
        {
            std::cout << e.what() << std::endl;
        }
    }
}
票数 5
EN

Stack Overflow用户

发布于 2020-07-21 17:04:21

你不能在线程之间捕获异常。当抛出异常时,调用堆栈展开,寻找捕获。每个线程都有自己的堆栈。另一种方法是使用某种全局变量或队列或其他机制将异常从工作线程传递到主线程。检查此Catching exception from worker thread in the main thread

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63010865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档