std::thread::joinable

< cpp‎ | thread‎ | thread

bool joinable() const noexcept;
(C++11 起)

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

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

参数

(无)

返回值

std::thread 对象标识活跃的执行线程则为 true,否则为 false

示例

#include <chrono>
#include <iostream>
#include <thread>
 
void foo()
{
    std::this_thread::sleep_for(500ms);
}
 
int main()
{
    std::cout << std::boolalpha;
 
    std::thread t;
    std::cout << "启动前, joinable: " << t.joinable() << '\n';
 
    t = std::thread{foo};
    std::cout << "启动后, joinable: " << t.joinable() << '\n';
 
    t.join();
    std::cout << "合并后, joinable: " << t.joinable() << '\n';
 
    t = std::thread{foo};
    t.detach();
    std::cout << "分离后, joinable: " << t.joinable() << '\n';
    std::this_thread::sleep_for(1500ms);
}

输出:

启动前, joinable: false
启动后, joinable: true
合并后, joinable: false
分离后, joinable: false

引用

  • C++23 标准(ISO/IEC 14882:2024):
  • 33.4.3.6 Members [thread.thread.member]
  • C++20 标准(ISO/IEC 14882:2020):
  • 32.4.2.5 Members [thread.thread.member]
  • C++17 标准(ISO/IEC 14882:2017):
  • 33.3.2.5 thread members [thread.thread.member]
  • C++14 标准(ISO/IEC 14882:2014):
  • 30.3.1.5 thread members [thread.thread.member]
  • C++11 标准(ISO/IEC 14882:2011):
  • 30.3.1.5 thread members [thread.thread.member]

参阅

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