【发布时间】:2017-02-15 00:26:15
【问题描述】:
#include <pthread.h>
#include <thread>
#include <iostream>
using namespace std;
struct A
{
~A()
{
cout << "~A()" << endl;
}
};
void* f(void*)
{
thread_local A a;
return 0;
}
int main()
{
pthread_t tid;
pthread_create(&tid, nullptr, f, nullptr);
this_thread::sleep_for(5min);
}
根据cppreference:
对象在线程开始时分配,在线程开始时释放 线程结束。每个线程都有自己的对象实例。仅有的 声明为
thread_local的对象具有此存储持续时间。
我只是想知道:
C++ 编译器如何知道何时创建和退出裸线程(而不是std::thread)?
换句话说:
C++标准保证A::~A()会在裸线程函数f完成后被调用吗?
【问题讨论】:
-
这很难从 C++ 标准的角度来回答,因为 C++ 标准没有像您使用它的方式那样的“裸线程”概念。但当然 C++ 线程将以某种特定于平台的方式实现,如果您碰巧直接编写相同的实现代码,您最终可能会得到相同的行为。
标签: c++ multithreading c++11 posix standards