【发布时间】:2021-06-08 14:07:08
【问题描述】:
我有一个在无限循环中运行的线程来做一些工作。现在我想顺利终止程序,没有任何错误,是否可以在没有连接的情况下终止线程并捕获异常?
我尝试了以下代码:
#include <iostream>
#include <thread>
#include <chrono>
#include <memory>
using namespace std;
void foo()
{
// simulate expensive operation
this_thread::sleep_for(chrono::seconds(1));
}
void bar()
{
// simulate expensive operation
while (true)
this_thread::sleep_for(chrono::seconds(1));
}
int main()
{
cout << "starting first helper...\n";
thread helper1(foo);
cout << "starting second helper...\n";
shared_ptr<thread> helper2 = make_shared<thread>(bar);
cout << "waiting for helpers to finish..." << endl;
helper1.join();
try {
helper2.reset(); // drop thread without join
} catch (exception e) {
cout << e.what() << endl;
}
cout << "done!\n";
}
我得到以下结果:
starting first helper...
starting second helper...
waiting for helpers to finish...
terminate called without an active exception
Aborted (core dumped)
看起来没有抛出异常。为什么?
【问题讨论】:
-
~thread调用std::terminate如果线程是可连接的。它不会抛出异常。销毁可连接线程是一个逻辑错误。
标签: c++ multithreading exception