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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…