学习C++多线程。
在我的例子中,线程helper1
and helper2
之前已完成执行main
线程完成。然而,程序崩溃了。我特地拿出来.join()
语句,查看程序的行为方式,期望没有错误,因为main()
calls std::terminate
其他两个线程完成后。
void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "t1\n";
}
void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "t2\n";
}
int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);
std::cout << "starting second helper...\n";
std::thread helper2(bar);
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "waiting for helpers to finish..." << std::endl;
//helper1.join();
//helper2.join();
std::cout << "done!\n";
}
我想说你的问题没有意义,因为它是基于错误的假设。唯一知道的方法that线程完成是指该线程的join()
返回。前join()
返回时,并不是“线程已完成”的情况。线程执行中的某些语句可能确实已经完成(例如消息的打印,或者更好的是原子变量的写入),但线程函数本身的完成并不可测量的除了加入以外的任何方式。
So none线程“已完成”,直到您加入它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)