命名空间
变体
操作

std::jthread::join

来自 cppreference.cn
< cpp‎ | thread‎ | jthread
 
 
并发支持库
线程
(C++11)
(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++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危险指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 中已弃用)
(C++11)(C++20 中已弃用)
内存排序
(C++11)(C++26 中已弃用)
原子操作的自由函数
原子标志的自由函数
 
 
void join();
(C++20 起)

阻塞当前线程,直到由 *this 标识的线程完成执行。

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

*this 本身不执行同步。从多个线程并发调用同一个 jthread 对象的 join() 构成数据竞争,导致未定义行为。

目录

[编辑] 参数

(无)

[编辑] 返回值

(无)

[编辑] 后置条件

joinable()false

[编辑] 异常

如果发生错误,抛出 std::system_error

[编辑] 错误条件

[编辑] 示例

#include <chrono>
#include <iostream>
#include <thread>
 
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::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++23 标准 (ISO/IEC 14882:2024)
  • 33.4.4.3 成员 [thread.jthread.mem]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 32.4.3.2 成员 [thread.jthread.mem]

[编辑] 参阅

允许线程独立于线程句柄执行
(public member function) [编辑]
检查线程是否可join,即是否可能在并行上下文中运行
(public member function) [编辑]
C documentation for thrd_join