std::jthread::join

< cpp‎ | thread‎ | jthread

 
 
线程支持库
线程
(C++11)
(C++20)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
闩与屏障
(C++20)
(C++20)
future
(C++11)
(C++11)
(C++11)
(C++11)
 
 
void join();
(C++20 起)

阻塞当前线程直至 *this 所标识的线程结束其执行。

*this 所标识的线程的完成同步于对应的从 join() 成功返回。

*this 自身上不进行同步。同时从多个线程在同一 jthread 对象上调用 join() 构成数据竞争,导致未定义行为。

参数

(无)

返回值

(无)

后条件

joinable()false

异常

若出现错误则为 std::system_error

错误条件

示例

#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 first helper...\n";
    std::jthread helper1(foo);
 
    std::cout << "starting second helper...\n";
    std::jthread helper2(bar);
 
    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();
 
    std::cout << "done!\n";
}

输出:

starting first helper...
starting second helper...
waiting for helpers to finish...
done!

引用

  • C++20 standard (ISO/IEC 14882:2020):
  • 32.4.3.2 Members [thread.jthread.mem]

参阅

容许线程从线程句柄独立开来执行
(公开成员函数)
检查线程是否可合并,即潜在地运行于平行环境中
(公开成员函数)