首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多线程示例输出说明

多线程示例输出说明
EN

Stack Overflow用户
提问于 2014-03-14 19:34:12
回答 1查看 58关注 0票数 0

请任何人向我解释一下下面代码的输出,我很困惑线程是如何执行连接命令的,而不让主线程打印Hellos语句。

代码语言:javascript
复制
    // 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;
    }

产出:

代码语言:javascript
复制
    *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!*

非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-14 19:48:20

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22414188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档