我是线程编程的新手,我面临着让我困惑的情况,我试图在我放在线程中的函数内部抛出异常,在main()函数中我有一个try and 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;
}
提前感谢!
发布于 2020-07-21 17:29:55
关于@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;
}
}
}
发布于 2020-07-21 17:04:21
你不能在线程之间捕获异常。当抛出异常时,调用堆栈展开,寻找捕获。每个线程都有自己的堆栈。另一种方法是使用某种全局变量或队列或其他机制将异常从工作线程传递到主线程。检查此Catching exception from worker thread in the main thread
https://stackoverflow.com/questions/63010865
复制相似问题