jeudi 30 mars 2017

Does the main thread run on blocking threads?

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?

  1. Why does it work this way?
  2. Main thread joins 1st thread.
  3. Main thread waits until 1st thread finishes.
  4. 1st thread finishes.
  5. Main thread continues in for loop and joins 2nd thread.
  6. Main thread waits until 2nd thread finishes.
  7. ... ... ...

If it keep cycling through the for loop when does the main thread actually get blocked to wait?

Aucun commentaire:

Enregistrer un commentaire