6

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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
mikol
  • 185
  • 1
  • 10

1 Answers1

7

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190