Reputation: 42379
#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);
}
According to 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.
I just wonder:
How does the C++ compiler know when a naked thread (rather than std::thread
) is created and exited?
In other words:
Does the C++ standard guarantee A::~A()
will be called after the naked thread function f
is finished?
Upvotes: 2
Views: 163
Reputation: 182857
The C++ standard says nothing about what happens when or after you call pthread_create
. So if you want to know about that, you'd have to look someplace other than the C++ standard. Unfortunately, the POSIX standard says nothing about C++ thread local objects. So the POSIX standard won't say anything either.
That means that whatever happens to happen on some particular platform is not guaranteed unless the documentation for that particular compiler, platform, or threading standard says something specific.
Upvotes: 4