在运行下面的代码后,就会报错:
terminate called without an active exception
#include <iostream>
#include <thread>
using namespace std;
class background_task {
public:
void operator() () const {
cout << "hello" << endl;
}
};
void say() {
}
int main() {
background_task task;
thread t(task);
//t.join();
return 0;
}
原因是主线程在任务线程还没有执行完成就退出了,销毁了一些资源,导致任务线程就异常了。要修复这个问题也很简单,就是调用join,等待子线程执行完成,代码如下:
#include <iostream>
#include <thread>
using namespace std;
class background_task {
public:
void operator() () const {
cout << "hello" << endl;
}
};
void say() {
}
int main() {
background_task task;
thread t(task);
t.join();
return 0;
}