作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
#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 :
The object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared
thread_local
have this storage duration.
我只是想知道:
C++ 编译器如何知道何时创建和退出裸线程(而不是 std::thread
)?
换句话说:
C++标准是否保证A::~A()
会在裸线程函数f
结束后被调用?
最佳答案
C++ 标准没有说明调用 pthread_create
时或之后发生的情况。因此,如果您想了解这一点,则必须查看 C++ 标准以外的其他地方。不幸的是,POSIX 标准对 C++ 线程局部对象只字不提。所以 POSIX 标准也不会说什么。
这意味着除非特定编译器、平台或线程标准的文档说明了具体内容,否则无法保证在特定平台上发生的任何事情。
关于c++ - "thread_local"是否适用于裸线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238713/
我是一名优秀的程序员,十分优秀!