<分区>
以下代码来自Dash
std::thread
的示例.
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
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();
// std::cout << "after join... \n";
helper2.join();
std::cout << "done!\n";
}
join blocks the current thread until the thread identified by *this finishes its execution.
线程是否在join
之后执行叫什么?
如果我添加 std::cout << "after join... \n"
第一次加入后,after join...
和 done!
会按顺序输出,没有延迟,就像放在第二个join
之后一样.
具体来说,整个效果是:无延迟地顺序打印前三行,然后休眠一段时间,最后无延迟地顺序打印后两行。
a.join();
b.join();
cout << "something...";
// or
a.join();
cout << "something...";
b.join();
让我困惑的是:为什么这两种方式效果一样?什么是join
究竟做什么?