IoT
IoT

Reputation: 639

Multi-Threading Example output explanation

Can anyone please explain to me the output of the below code, I am confused how the threads are executing joining command without letting the main thread to print the Hellos sentences

    // 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 3 threads...\n";
      std::thread t1 (pause_thread,10);
      std::thread t2 (pause_thread,5);
      std::thread t3 (pause_thread,3);
      std::cout << "Done spawning threads. Now waiting for them to join:\n";
      t1.join();
      std::cout << "Hello 1!\n";
      t2.join();
      std::cout << "Hello 2!\n";
      t3.join();
      std::cout << "Hello 3!\n";
      std::cout << "All threads joined!\n";

      return 0;
    }

The output:

    *Spawning 3 threads...

    Done spawning threads. Now waiting for them to join:

    pause of 3 seconds ended

    pause of 5 seconds ended

    pause of 10 seconds ended

    Hello 1!

    Hello 2!

    Hello 3!

    All threads joined!*

Thanks a lot.

Upvotes: 0

Views: 64

Answers (1)

vines
vines

Reputation: 5225

join() blocks until the thread finishes. If the thread finishes before a call to join() is made, subsequent join() will return immediately. Thus, when you put several join() statements in a sequence, you'll block there until all the threads finish, no matter in what order they actually do.

Note that join() blocks the thread you call it from, and not the thread you call it for. I.e., in the code snippet, the main() thread will wait, but t1, t2 and t3 will go on until they finish.

Upvotes: 1

Related Questions