当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ Thread join用法及代码示例


描述

它在线程执行完成后返回。

声明

以下是 std::thread::join 函数的声明。

void join();

C++11

void join();

参数

返回值

异常

No-throw guarantee─ 从不抛出异常。

数据竞争

对象被访问。

示例

在下面的 std::thread::join 示例中。

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

void foo() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

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

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

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

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

输出应该是这样的——

starting helper...
starting another helper...
waiting for helpers to finish...
done!

相关用法


注:本文由纯净天空筛选整理自 C++ Thread Library - Function join。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。