Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is std::thread destructor called?

Tags:

c++

stdthread

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.

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?

like image 991
mikol Avatar asked May 26 '19 07:05

mikol


People also ask

Why is my destructor being called?

Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends.

Is the destructor always called?

No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

Is destructor called after return?

While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.

Is destructor called on exit?

No, most destructors are not run on exit() . Essentially, when exit is called static objects are destroyed, atexit handlers are executed, open C streams are flushed and closed, and files created by tmpfile are removed.


1 Answers

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?

No it isn't destroyed, but marked joinable(). So yes you can still join() it.

Otherwise as from the title of your question ("When is std::thread destructor called?") and what you say in your post

I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.

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.

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.

like image 179
πάντα ῥεῖ Avatar answered Sep 21 '22 09:09

πάντα ῥεῖ