std::jthread::joinable
来自 cppreference.cn
bool joinable() const noexcept; |
(C++20 起) | |
检查 std::jthread
对象是否标识了一个活跃的执行线程。具体而言,如果 get_id() != std::jthread::id(),则返回 true。因此,默认构造的 jthread
不可 присоеди。
一个已完成代码执行但尚未被 присоеди 的线程仍被视为一个活跃的执行线程,因此可 присоеди。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
如果 std::jthread
对象标识了一个活跃的执行线程,则返回 true,否则返回 false。
[编辑] 示例
运行此代码
#include <chrono> #include <iostream> #include <thread> using namespace std::chrono_literals; void foo() { std::this_thread::sleep_for(500ms); } int main() { std::cout << std::boolalpha; std::jthread t; std::cout << "before starting, joinable: " << t.joinable() << '\n'; t = std::jthread{foo}; std::cout << "after starting, joinable: " << t.joinable() << '\n'; t.join(); std::cout << "after joining, joinable: " << t.joinable() << '\n'; t = std::jthread{foo}; t.detach(); std::cout << "after detaching, joinable: " << t.joinable() << '\n'; }
输出
before starting, joinable: false after starting, joinable: true after joining, joinable: false after detaching, joinable: false
[编辑] 参考
- 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]
[编辑] 另请参阅
返回线程的 id (公共成员函数) | |
等待线程完成其执行 (公共成员函数) | |
允许线程独立于线程句柄执行 (公共成员函数) |