多线程示例输出说明

时间:2014-03-14 19:34:13

标签: c++11

任何人都可以向我解释下面代码的输出,我很困惑线程如何执行加入命令而不让主线程打印Hellos句子

    // 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;
    }

输出:

    *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!*

非常感谢。

1 个答案:

答案 0 :(得分:1)

join()阻塞,直到线程结束。如果线程在调用join()之前完成,则后续join()将立即返回。因此,当您在序列中放入多个join()语句时,您将阻止所有线程完成,无论它们实际执行的顺序如何。

请注意,join()会阻止您调用它的线程,而不是您调用它的线程。即,在代码段中,main()线程将等待,但t1t2t3将一直持续到完成。