Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

c++ - Thread Specific Data vs Thread Local Storage

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 from dlopened shared library, see this bug), because its use does not involve malloc (with the same exception).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...