[PATCH] Destructor support for C++11 thread_local variables

Siddhesh Poyarekar siddhesh@redhat.com
Wed Oct 10 15:36:00 GMT 2012


Hi,

C++11 introduces the thread_local scope for variables that have thread
scope.  These variables are similar to the TLS variables declared with
__thread with a few added features.  One of the key features is that
they support non-trivial constructors and destructors that are called
on first-use and thread exit respectively.  Additionally, if the current
thread results in a process exit, destructors for thread_local
variables should be called for this thread as well.

Jason Merrill has already put in this support into gcc trunk.  The
compiler can handle constructors, but destructors need more runtime
context.  It could be possible that a dynamically loaded library
defines and constructs a thread_local variable, but is dlclose()'d
before thread exit.  The destructor of this variable will then have the
rug pulled from under it and crash. As a result, the dynamic linker
needs to be informed so as to not unload the DSO.

Attached patch adds a __cxa_thread_atexit_impl that handles the
destructors and their call order for libstdc++ and also ensures that
the dynamic linker does not unload the dso that defines a thread_local
variable.

I have written a small wiki page detailing this so that other compilers
may use this as well for thread_local implementation:

http://sourceware.org/glibc/wiki/Destructor%20support%20for%20thread_local%20variables

I have tested this by hacking up libstdc++ from gcc HEAD to call
__cxa_thread_atexit_impl instead of its internal fallback
implementation.

A lot of the ideas for this patch came from Jakub Jelinek.  One could
find Jason's changes for thread_local support in gcc/libstdc++
in the latest trunk.  It doesn't directly check for and call
__cxa_thread_atexit_impl yet, but I understand it should be in soon.

OK to commit?

Regards,
Siddhesh

ChangeLog:

	* include/stdlib.h (__cxa_thread_atexit_impl): Declare.
	(__call_tls_dtors): Likewise.
	* stdlib/Makefile (routines): Add __cxa_thread_atexit_impl.
	* stdlib/Versions (GLIBC_2.17): Likewise.
	(GLIBC_PRIVATE): Add __call_tls_dtors.
	* stdlib/cxa_thread_atexit_impl.c: New file with helper function
	for libstdc++.
	* stdlib/exit.c (__run_exit_handlers): Call __call_tls_dtors.

nptl/ChangeLog:

	* pthread_create.c (start_thread): Call __call_tls_dtors.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: thread-local.patch
Type: text/x-patch
Size: 6077 bytes
Desc: not available
URL: <http://sourceware.org/pipermail/libc-alpha/attachments/20121010/a2a6a3ed/attachment.bin>


More information about the Libc-alpha mailing list