当所有其他线程在主线程之前完成时,为什么仍然需要.join? [英] Why .join is still necessary when all other thread have finished before the main thread?
问题描述
学习C ++多线程.
在我的示例中,线程helper1
和helper2
在main
线程完成之前已完成执行.但是,程序崩溃.我专门取出了.join()
语句,以查看程序的行为方式,不会出现任何错误,因为main()
在另外两个线程完成之后调用std::terminate
.
Learning C++ multi-threading.
In my example, thread helper1
and helper2
have finished executing before the main
thread finished. However, program crashes. I specifically, took out .join()
statements, to see how program would behave, expecting no errors, since main()
calls std::terminate
after two other threads have finished.
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";
}
推荐答案
我会说您的问题没有道理,因为它是基于错误的假设.知道线程已完成的唯一方法是线程的join()
返回时.在join()
返回之前,并非线程已完成".的确,线程执行过程中的某些语句已经完成(例如,消息的打印,或者更好的是,原子变量的写入),但是线程函数本身的完成是不可衡量的.除了通过加入以外的任何方式.
I'd say that your question doesn't make sense, because it's based on a false assumption. The only way to know that a thread has finished is when the thread's join()
returns. Before join()
returns, it is not the case that "the thread has finished". It may be true that some statement within the thread's execution has completed (e.g. the printing of a message, or better, the writing of an atomic variable), but the completion of the thread function itself is not measurable in any way other than by joining.
因此,在您加入线程之前,没有 个线程已经完成".
So none of the threads "have finished" until you join them.
这篇关于当所有其他线程在主线程之前完成时,为什么仍然需要.join?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!