c++ std::thread::joinable

发布时间 2023-07-26 21:48:47作者: BuzzWeek

std:?:joinable

  • 默认构造的thread对象 not joinable
  • join/detach之后 not joinable
  • 不能反复join/detach,会崩
  • 当前线程会阻塞在join()调用处
  • detach()不会阻塞当前线程,但是主进程结束后detach线程也会结束
  • 也可以完全不join/detach,但thread对象被析构后相应线程会被Terminate

joinable test

#include <iostream>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
 
void foo()
{
    std::this_thread::sleep_for(500ms);
}
 
int main()
{
    std::cout << std::boolalpha;
 
    std::thread t;
    std::cout << "before starting, joinable: " << 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';
 
    t = std::thread{foo};
    t.detach();
    std::cout << "after detaching, joinable: " << t.joinable() << '\n';
    std::this_thread::sleep_for(1500ms);
}
before starting, joinable: false
after starting, joinable: true
after joining, joinable: false
after detaching, joinable: false

terminate

~thread() noexcept {
    if (joinable()) {
        _STD terminate();
    }
}

参考

https://en.cppreference.com/w/cpp/thread/thread/joinable