简体   繁体   English

何时调用std :: thread析构函数?

[英]When is std::thread destructor called?

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope. 我知道在主出口上调用std::thread析构函数,或者当一个线程对象超出作用域时。

But is it also destroyed when a function that it is calling is done executing? 但它正在调用的函数执行时是否也会被销毁?
If not what happens to such a thread, can I still join() it? 如果不是这样的线程发生了什么,我还可以join()吗?

But is it also destroyed when a function that it is calling is done executing? 但它正在调用的函数执行时是否也会被销毁? If not what happens to such a thread, can I still join() it? 如果不是这样的线程发生了什么,我还可以join()吗?

No it isn't destroyed, but marked joinable() . 不,它没有被销毁,但标记为joinable() So yes you can still join() it. 所以是的,你仍然可以join()它。

Otherwise as from the title of your question ( "When is std::thread destructor called?" ) and what you say in your post 否则从问题的标题( “什么时候调用std :: thread析构函数?” )和你在帖子中说的话

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope. 我知道在主出口上调用std :: thread析构函数,或者当一个线程对象超出作用域时。

It's like with any other instance: The destructor is called when the instance goes out of scope or delete is called in case the instances were allocated dynamically. 它与任何其他实例一样:当实例超出范围时调用析构函数,或者在动态分配实例时调用delete

Here's a small example code 这是一个小例子代码

#include <thread>
#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

void foo() {
    std::cout  << "Hello from thread!" << std::endl;
}

int main() { 
    std::thread t(foo);
    std::this_thread::sleep_for(1s);
    std::cout << "t.joinable() is " << t.joinable() << std::endl;
    t.join();
}

The output is 输出是

 Hello from thread! t.joinable() is 1 

See it live . 现场观看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM