一:解决什么问题
join:主线程等待子线程执行结束
解决了困扰我已久的
wait在notify前面的时候,线程怎么join的问题
二:答案:在析构函数里join
三:测试:不在析构函数里join的报错
#include <thread>
#include <iostream>
#include <chrono>
void func1()
{
std::cout << "hello world" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "enjoy" << std::endl;
}
int main()
{
std::thread th1(func1);
th1.join();
std::cout << "test" << std::endl;
return 0;
}
本文探讨了在多线程编程中如何使用join方法确保主线程等待子线程执行完毕,特别是在析构函数中的应用。通过示例代码展示了不正确使用join可能导致的错误,并强调了在析构函数中调用join的重要性。
1375

被折叠的 条评论
为什么被折叠?



