Please help me with a simple question about the output of the following code.
I thought that a thread is executed only when the join() or detach() function is called.
So, I expect the output to print only "pause of 2 seconds ended , ID = 59306", and not to print "pause of 1 seconds ended , ID = 10218" because I thought that only thread 2 would be executed, and thread 1 would NOT be executed. But, I was wrong.
In reality, the output actually prints both of the lines mentioned above, which means both thread 1 and 2 are executed. Is it true ?
Would you please explain to me how the code actually execute both threads ?
==========================
#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 , ID = " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::cout << "Spawning 2 threads...\n";
std::thread t1 (pause_thread,1);
std::thread t2 (pause_thread,2);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
//t1.join();
t2.join();
//t1.detach();
//t2.detach();
std::cout << "All threads joined!\n";
return 0;
}
Actual Output :
Spawning 2 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended , ID = 10218
pause of 2 seconds ended , ID = 59306
All threads joined!
===================
Update:
Thanks to all comments and answers from everyone.
Now, I understand my incorrect logic because I mistakenly thought that a thread were executed only when the join() or detach() function is called.
I realize that a thread is executed as soon as it is created without the need to call join() or detach().
join() : In the main() function, after we call join() on a thread, the main() function will be blocked until the thread completes. After the thread completes, the main() function will resume, and the output from the thread will be shown along with any remaining output from the main() function.
detach() : In the main() function, if we call detach() on a thread, then, both the main() function and thread can run concurrently, and they are not blocked by each other or do not depend on each other in any way. In this case, if the main() function finishes before the detached thread completes, then we can only see the output from the main() function and NOT from the detached thread. However, if the detached thread finishes before the main() function completes, then we can see the output from both the thread and the main() function.