Ref:
http://www.cplusplus.com/reference/thread/thread/join/
In below code, what I expect is t2 should print "pause of 2 seconds ended" in 2 seconds after t1 print, t3 should print in 3 seconds after t2 print and so on.
But the result seems t2 print in one second after t1 print, t3 print in 1 second after t2 print, that means each thread runs parallel.
To my understanding about function join's use case, when t1 is joined, it will block the thread of execution using the function pause_thread(int n), so t2 should not be executed until t1 completed, therefore t2 should print in 2 seconds after t1 print. Can you explain the reason? Thanks!
// example for thread::join
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning 6 threads...\n";
std::thread t1(pause_thread, 1);
std::thread t2(pause_thread, 2);
std::thread t3(pause_thread, 3);
std::thread t4(pause_thread, 4);
std::thread t5(pause_thread, 5);
std::thread t6(pause_thread, 6);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
std::cout << "All threads joined!\n";
return 0;
}