std::thread::join
来自 cppreference.cn
| void join(); |
(C++11 起) | |
阻塞当前线程,直到由 *this 标识的线程执行完毕。
由 *this 标识的线程的完成与 join() 相应的成功返回“同步”。
对 *this 本身不执行同步。从多个线程并发地对同一个线程对象调用 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::thread helper1(foo); std::cout << "starting second helper...\n"; std::thread 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.3.6 成员 [thread.thread.member]
- C++20 标准 (ISO/IEC 14882:2020)
- 32.4.2.5 成员 [thread.thread.member]
- C++17 标准 (ISO/IEC 14882:2017)
- 33.3.2.5 线程成员 [thread.thread.member]
- C++14 标准 (ISO/IEC 14882:2014)
- 30.3.1.5 线程成员 [thread.thread.member]
- C++11 标准 (ISO/IEC 14882:2011)
- 30.3.1.5 线程成员 [thread.thread.member]
[编辑] 另请参阅
| 允许线程独立于线程句柄执行 (公共成员函数) | |
| 检查线程是否可join,即是否可能在并行上下文中运行 (公共成员函数) | |
| C 文档 关于 thrd_join
| |