Namespaces
Variants

std::jthread:: join

From cppreference.net

Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
void join ( ) ;
(自 C++20 起)

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

* this 标识的线程完成操作 join() 成功返回的对应操作 实现同步

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

目录

参数

(无)

返回值

(无)

后置条件

joinable() false

异常

std::system_error 如果发生错误。

错误条件

示例

#include <chrono>
#include <iostream>
#include <thread>
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++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]

参见

允许线程独立于线程句柄执行
(公开成员函数)
检查线程是否可连接,即是否可能在并行上下文中运行
(公开成员函数)
C 文档 关于 thrd_join