When I started to look into threading in c++11, I thought that .join()
was used to make a blocking operation on the main thread and std::async()
was used to run non-blocking threads.
This answer explains std:async()
pretty well in my opinion. https://stackoverflow.com/a/15035157/1770034
But I wanted to understand the join method better. I found several examples like this: https://stackoverflow.com/a/11229853/1770034 Where only 1 thread is created from the main thread.
Then I found this https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
Snippet of Code from site:
#include <iostream>
#include <thread>
static const int num_threads = 10;
//This function will be called from a thread
void call_from_thread(int tid) {
std::cout << "Launched by thread " << tid << std::endl;
}
int main() {
std::thread t[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
return 0;
}
The part I'm curious about this this part right here:
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
If the main thread stops to wait until .join()
is complete, how can the loop run to join more threads? The fact it works is great! But, why does it work?
Why does it work this way? This was my impression of how it worked.
- Main thread joins 1st thread.
- Main thread waits until 1st thread finishes.
- 1st thread finishes.
- Main thread continues in for loop and joins 2nd thread.
- Main thread waits until 2nd thread finishes.
- ... ... ...
If it keep cycling through the for loop when does the main thread actually get blocked to wait?
Edit
Example:
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
t[i].join();
// --- Perform some long operation here ---
}
When would the long operation take place?