std::thread::joinable

< cpp‎ | thread‎ | thread

 
 
线程支持库
线程
(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)
 
 
bool joinable() const noexcept;
(C++11 起)

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

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

参数

(无)

返回值

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

示例

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::thread 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.2.5 Members [thread.thread.member]
  • C++17 standard (ISO/IEC 14882:2017):
  • 33.3.2.5 thread members [thread.thread.member]
  • C++14 standard (ISO/IEC 14882:2014):
  • 30.3.1.5 thread members [thread.thread.member]
  • C++11 standard (ISO/IEC 14882:2011):
  • 30.3.1.5 thread members [thread.thread.member]

参阅

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