The following code is from Dash
's example for 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.
Does thread execute after join
called?
If I add std::cout << "after join... \n"
after the first join, the after join...
and done!
will output sequentially, without delay, which just like being put after second join
.
To be specific, the whole effect is : print the first three lines sequentially without delay, then sleep for some while, final print the last two lines sequentially without delay.
a.join();
b.join();
cout << "something...";
// or
a.join();
cout << "something...";
b.join();
What confused me is : Why do the two ways have same effect? What does join
do exactly?