我们先看一段代码:
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
volatile bool flag = false;
void f1() {
for (int i = 0; i < 1000; ++i) {
if (flag) cout << i << " catched" << endl;
else cout << i << " running" << endl;
usleep(10000);
}
}
void f2() {
sleep(1);
flag = true;
throw 1;
}
void run1() {
thread thr(f1);
f2();
thr.join();
}
int main()
{
try {
run1();
} catch(...) {
}
while(1);
}
这段代码中,我们在run1里面发射了一个线程f1,f1是做一个计数工作,在run1里面运行f2,f2在休眠1秒之后抛异常。
运行结果是: 当f2抛异常之后,程序就挂掉了。
这是为什么呢?因为在f2抛出异常之后,run1发生调用栈回退的时候,析构thr了。在析构thr的时候,我们可以看一下gcc的源代码:
~thread()
{
if (joinable())
std::terminate();
}
一旦这个句柄