std::jthread:: join
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
| Operations | ||||
|
jthread::join
|
||||
| Stop token handling | ||||
| Non-member functions | ||||
|
void
join
(
)
;
|
(自 C++20 起) | |
阻塞当前线程,直到由 * this 标识的线程完成其执行。
由
*
this
标识的线程完成操作
与
从
join()
成功返回的对应操作
实现同步
。
不会对 * this 本身执行同步操作。从多个线程并发地对同一 jthread 对象调用 join ( ) 将构成数据竞争,导致未定义行为。
目录 |
参数
(无)
返回值
(无)
后置条件
joinable() 为 false 。
异常
std::system_error 如果发生错误。
错误条件
- resource_deadlock_would_occur 如果 this - > get_id ( ) == std:: this_thread :: get_id ( ) (检测到死锁)。
- no_such_process 如果线程无效。
- invalid_argument 如果 joinable() 为 false 。
示例
#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
|
|