gpt4 book ai didi

c++ - c++ 多线程递归调用终止

转载 作者:行者123 更新时间:2023-12-01 14:35:10 26 4
gpt4 key购买 nike

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

1。在抛出“char const*”实例后调用终止

2。递归终止调用

下面是我的代码

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

提前致谢!

最佳答案

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

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

关于c++ - c++ 多线程递归调用终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63010865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com