I've read Kerrisk's The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Chapter 31 on Threads. The chapter include Thread Specific Data (Section 31.3.4) and Thread Local Storage (Section 31.4). The topics were covered on pages 663-669.
Thread Specific Data (pthread_key_create
, pthread_setspecific
, pthread_getspecific
, and friends) looks more powerful, but appears to be a little more cumbersome to use, and appears to use the memory manager more frequently.
Thread Local Storage (__thread
on static and global declarations) looks a little less powerful since its limited to compile time, but its appears to be easier to use, and appears to stay out of the memory manager at runtime.
I could be wrong about the runtime memory manager since there could be code behind the scenes that calls pthread_key_create
when it encounters __thread
variables.
Kerrisk did not offer a compare/contrast of the two strategies, and he did not make a recommendation on when to use which in a given situation.
To add context to the question: I'm evaluating a 3rd party library. The library uses globals, does not utilize locking, and I want to use it in a multi-threaded program. The program uses threading to minimize network latencies.
Is there a hands down winner? Or are there different scenarios that warrant using one or the other?
The
pthread_key_create
and friends are much older, and thus supported on more systems.The
__thread
is a relative newcomer, is generally much more convenient to use, and (according to Wikipedia) is supported on most POSIX systems that still matter: Solaris Studio C/C++, IBM XL C/C++, GNU C, Clang and Intel C++ Compiler (Linux systems).The
__thread
also has a significant advantage that it is usable from signal handlers (with the exception of using__thread
fromdlopen
ed shared library, see this bug), because its use does not involvemalloc
(with the same exception).