std::jthread::joinable

< cpp‎ | thread‎ | jthread

 
 
线程支持库
线程
(C++11)
(C++20)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
闩与屏障
(C++20)
(C++20)
future
(C++11)
(C++11)
(C++11)
(C++11)
 
 
[[nodiscard]] bool joinable() const noexcept;
(C++20 起)

检查 std::jthread 对象是否标识活跃的执行线程。具体而言,若 get_id() != std::jthread::id() 则返回 true 。故默认构造的 jthread 不可结合。

结束执行代码,但仍未结合的线程仍被当作活跃的执行线程,从而可结合。

参数

(无)

返回值

若 jthread 对象标识活跃的执行线程则为 true ,否则为 false

示例

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::jthread t;
    std::cout << "before starting, joinable: " << std::boolalpha << t.joinable()
              << '\n';
 
    t = std::thread(foo);
    std::cout << "after starting, joinable: " << t.joinable() 
              << '\n';
 
    t.join();
    std::cout << "after joining, joinable: " << t.joinable() 
              << '\n';
}

输出:

before starting, joinable: false
after starting, joinable: true
after joining, joinable: false

引用

  • C++20 standard (ISO/IEC 14882:2020):
  • 32.4.3.2 Members [thread.jthread.mem]

参阅

返回线程的 id
(公开成员函数)
等待线程完成其执行
(公开成员函数)
容许线程从线程句柄独立开来执行
(公开成员函数)