什么时候调用 std::thread 析构函数?
When is std::thread destructor called?
我知道 std::thread
析构函数在主出口或线程对象超出范围时调用。
但是当它调用的函数执行完毕时它是否也被销毁了?
如果不是这样的帖子怎么办,我还能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?
不,它没有被销毁,但被标记为 joinable()
。所以是的,你仍然可以 join()
它。
否则从你的问题标题 ("When is std::thread destructor called?") 和你在 post
中所说的
I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.
这与任何其他实例一样:当实例超出范围时调用析构函数,或者在动态分配实例的情况下调用 delete
。
这是一个小示例代码
#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();
}
输出为
Hello from thread!
t.joinable() is 1
看到了live.
我知道 std::thread
析构函数在主出口或线程对象超出范围时调用。
但是当它调用的函数执行完毕时它是否也被销毁了?
如果不是这样的帖子怎么办,我还能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?
不,它没有被销毁,但被标记为 joinable()
。所以是的,你仍然可以 join()
它。
否则从你的问题标题 ("When is std::thread destructor called?") 和你在 post
中所说的I know that std::thread destructors are called on main exit, or when a thread object goes out of scope.
这与任何其他实例一样:当实例超出范围时调用析构函数,或者在动态分配实例的情况下调用 delete
。
这是一个小示例代码
#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();
}
输出为
Hello from thread! t.joinable() is 1
看到了live.