std::jthread::join
来自 cppreference.cn
void join(); |
(C++20 起) | |
阻塞当前线程,直到由 *this 标识的线程完成执行。
由 *this 标识的线程的完成与 join()
对应的成功返回**同步**。
在 *this 本身不执行同步。从多个线程并发调用同一个 jthread 对象的 join() 构成数据竞争,导致未定义行为。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
(无)
[编辑] 后置条件
joinable() 为 false。
[编辑] 异常
如果发生错误,抛出 std::system_error。
[编辑] 错误条件
- 如果 this->get_id() == std::this_thread::get_id()(检测到死锁),抛出 resource_deadlock_would_occur。
- 如果线程无效,抛出 no_such_process。
- 如果 joinable() 为 false,抛出 invalid_argument。
[编辑] 示例
运行此代码
#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
|