tower120
tower120

Reputation: 5265

c++ thread_local destructors with pthread destructors

I want to do some work after all C++ thread_local destructors called. This is platform specific - Android, so I have access to pthreads.

The question is, when pthread_key_created destructors should be called, before or after C++ thread_local destructors? Or they can be interleaved?

I tested On Linux Mint and pthread destructors called after C++ 's.

Upvotes: 0

Views: 1566

Answers (2)

ephemient
ephemient

Reputation: 204964

bionic/pthread_exit.cpp currently has the same order:

void pthread_exit(void* return_value) {
  // Call dtors for thread_local objects first.
  __cxa_thread_finalize();
  // Call the TLS destructors.
  pthread_key_clean_all();

However, this is not documented behavior and you should not build something relying on it.

Upvotes: 1

Florian Weimer
Florian Weimer

Reputation: 33727

libstdc++ from GCC uses pthread_key_create in case the platform does not provide __cxa_thread_atexit_impl. In this case, C++ destructors run somewhere in the middle of the POSIX destructors.

To my knowledge, there is no standard which requires any particular behavior here because C++ does not know about POSIX and POSIX does not know about C++, so neither standard says what happens here. There are also some corner cases involving the resurrection of thread-local data during thread destruction which will vary among implementations. (A typical example is a per-thread logger object which is used to log from destructors of thread-local variables.)

Upvotes: 0

Related Questions