std::thread::join文档说“它会阻塞当前线程,直到由 *this 标识的线程完成执行。”
但我很困惑,当我创建多个线程并将它们一个接一个地加入时,似乎前一个 'helper1.join' 没有阻止下一个 'helper2.join'语句是因为根据输出结果有时t1先完成,有时t2先完成。我如何理解这种情况?
示例代码:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"this foo"<<endl;
}
void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
cout<<"this one"<<endl;
}
int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);
std::cout << "starting second helper...\n";
std::thread helper2(bar);
std::cout << "waiting for helpers to finish..." << std::endl;
helper1.join();
helper2.join();
std::cout << "done!\n";
}
最佳答案
在您的代码中,您有三个线程:两个您启动的线程和一个由操作系统启动的主线程。 join
只影响执行它的主线程,foo
和 bar
线程在创建时立即启动。哪个首先打印其输出取决于调度程序,并且 - 正如您注意到的那样 - 未确定。 join
调用仅确保“完成!”在创建的线程完成后打印。
关于c++ - C++线程连接会立即返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582537/