C++ 线程 : what does join do exactly?

标签 c++ multithreading join

<分区>

以下代码来自Dash std::thread 的示例.

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
    std::cout << "starting first helper...\n";
    std::thread helper1(foo);

    std::cout << "starting second helper...\n";
    std::thread helper2(bar);

    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    // std::cout << "after join... \n";
    helper2.join();

    std::cout << "done!\n";
}

join blocks the current thread until the thread identified by *this finishes its execution.

线程是否在join之后执行叫什么?

如果我添加 std::cout << "after join... \n"第一次加入后,after join...done!会按顺序输出,没有延迟,就像放在第二个join之后一样.

具体来说,整个效果是:无延迟地顺序打印前三行,然后休眠一段时间,最后无延迟地顺序打印后两行。

a.join();
b.join();
cout << "something...";
// or
a.join();
cout << "something...";
b.join();

让我困惑的是:为什么这两种方式效果一样?什么是join究竟做什么?

最佳答案

您的两个线程同时启动并执行相同的长度。因此 join 在你的情况下并没有做太多 - 两个线程同时开始并同时结束。

  1. 线程1启动,开始休眠1秒
  2. 线程2启动,开始休眠1秒
  3. Join on 1 called - 程序将等待 1 秒以等待线程 1 完成
  4. 这意味着线程 2 也完成了
  5. Join on 2 called,这只是直通,因为线程 2 已经完成

如您所见,在第 5 步之前或之后打印任何内容都没有任何改变。

一个更好的例子是这样的:

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

void foo()
{
    // simulate expensive operation
    cout << "Foo Start" << endl;
    this_thread::sleep_for(chrono::seconds(1));
    cout << "Foo Stop" << endl;
}

void bar()
{
    // simulate expensive operation
    cout << "Bar Start" << endl;
    this_thread::sleep_for(chrono::seconds(2));
    cout << "Bar Stop" << endl;
}

int main()
{
    thread helper1(foo);
    thread helper2(bar);

    helper1.join();
    cout << "Joined Foo... \n";
    helper2.join();
    cout << "Joined Bar... \n";
}

您会观察到,如果线程 foo 持续 1 秒而线程 bar 持续 2 秒,那么“Joined Foo”和“Joined Bar”输出之间将有 1 秒的延迟。如果将 foo 的持续时间反转为 2 秒,bar 的持续时间反转为 1 秒,那么“Joined Foo”输出将在 2 秒后打印,然后立即打印“Joined Bar”。

关于C++ 线程 : what does join do exactly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303393/

相关文章:

c++ - 我如何读取文件的最后一行

java - 试图阻止Java中同时运行的单个线程

c++ - 在 Windows Server 2008R2 上启动调试构建时出现问题

java - 如何从Java中的多个线程获取和处理对象?如何创建 Future 的多个实例

c# - 设置并发作业的最大值 Quartz.Net

MYSQL:从多个表返回计数

nhibernate - 左连接、非重复和使用 QueryOver 进行分页

mysql使用连接查询将两个表与注册表连接起来

c++ - gcc/g++ 与 icc

c++ - 如何使用 Direct3D 设备管理器?