I've done a test but I don't figure out the order of execution of threads.
Here is my code:
void func1()
{
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
std::cout<<"func1"<<std::endl;
}
void func2()
{
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
std::cout<<"func2"<<std::endl;
}
int main()
{
std::thread t(func1);
std::thread t2(func2);
t.join();
t2.join();
std::this_thread::sleep_for(std::chrono::milliseconds(8000));
cout << "Hello World" << endl;
return 0;
}
In this case, I got the result below:
wait for 4 sec ---> "func1func2\n\n" is shown ---> wait for 8 sec ---> "Hello world" is shown.
If I change the order of the code in main
as below:
t.join();
std::this_thread::sleep_for(std::chrono::milliseconds(8000));
t2.join();
I can get the same result just as above.
However, if I change it like this:
std::this_thread::sleep_for(std::chrono::milliseconds(8000));
t.join();
t2.join();
The result becomes:
wait for 4 sec ---> "func1func2\n\n" is shown ---> wait for 4 sec ---> "Hello world" is shown.
It seems that the main thread and t and t2 waits for 4 sec at the same time in this case.
How to explain all of these?