首页 > 解决方案 > 终止调用递归 C++ 多线程

问题描述

我是线程新手,遇到了让我困惑的情况,我尝试在放入线程的函数中抛出异常,在 main() 函数中我有一个 try 和 catch 块,但是我仍然收到这些错误:

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

2. terminate called recursively

下面是我的代码

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;
}

提前致谢 !

标签: c++multithreading

解决方案


要详细说明@DeltA的答案:std::thread您可以使用指针来处理和传递异常,而不是使用它,std::future因为它将抛出的异常存储在其共享状态中:

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;
        }
    }
}

推荐阅读