std::thread。join
时间: 2023-12-13 10:33:47 浏览: 40
std::thread是C++11中引入的线程库,用于创建和管理线程。join()是std::thread类的一个成员函数,用于等待线程执行完毕并回收线程资源。如果不调用join(),则线程对象的析构函数会自动调用,但是如果线程还没有执行完毕,程序会终止,这会导致资源泄漏和未定义行为。以下是两种确保在主线程结束前调用join()的方法:
1.使用创建局部对象的方法:
```c++
class mythread {
private:
std::thread &m_t;
public:
explicit mythread(std::thread &t):m_t(t){}
~mythread() {
if(m_t.joinable()) {
m_t.join();
}
}
mythread(mythread const&) = delete;
mythread& operator=(mythread const&) = delete;
};
void test() {
// 线程执行的代码
}
bool do_other_things() {
// 其他代码
}
int main() {
std::thread t(test);
mythread q(t);
if(do_other_things()) {
return -1;
}
return 0;
}
```
2.使用try-catch语句:
```c++
void test() {
// 线程执行的代码
}
bool do_other_things() {
// 其他代码
}
int main() {
std::thread t(test);
try {
do_other_things();
} catch(...) {
throw;
}
t.join();
return 0;
}
```