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?
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.