std::thread::join document says that "It blocks the current thread until the thread identified by *this finishes its execution."
But I am confused that when I create several threads and join them one by one, it seems that the previous 'helper1.join' not blocked next one 'helper2.join' statement because according to the output result sometimes t1 finish first, sometimes t2 finish first. How can I understand this situations?
example code:
#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";
}
Aucun commentaire:
Enregistrer un commentaire