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. http://ift.tt/2nz22so
But I wanted to understand the join method better. I found several examples like this: http://ift.tt/2oeny8Q Where only 1 thread is created from the main thread.
Then I found this http://ift.tt/1dBg4Dv
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?
- 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?
Aucun commentaire:
Enregistrer un commentaire