Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_key_t vs local variable

I am developing a multithreaded program in C++ with Pthread where I need to allocate local memory in each thread. After googling I found pthread_key_t type which is some kind of map which allow you to allocate memory in the TLS.

So my question is what is the difference between a local variable in the thread function and a pthread_key_t? And can you give a correct usage example of pthread_key_t?

like image 759
Vicente Bolea Avatar asked Feb 07 '14 10:02

Vicente Bolea


People also ask

What is __ thread in C?

The __thread storage class marks a static variable as having thread-local storage duration. This means that in a multi-threaded application a unique instance of the variable is created for each thread that uses it and destroyed when the thread terminates.

What is thread local storage used for?

Thread Local Storage (TLS) is the mechanism by which each thread in a given multithreaded process allocates storage for thread-specific data. In standard multithreaded programs, data is shared among all threads of a given process, whereas thread local storage is the mechanism for allocating per-thread data.


2 Answers

The difference between thread-local storage and local variables are that thread-local storage does not need to be local to a function. Regular local variables may no longer be accessed as soon as the function that declares them returns. Thread-specific storage accessed with pthread_getspecific and pthread_setspecific may be safely used after the function that created it exits.

You can think of thread-local variables as thread-specific global variables, shared among functions running in the same thread. They are often used to make legacy code that makes heavy use of global variables multithreading-safe. As with all global variables, they should be used with care — if you can get away with only using local variables, by all means do so. If you do need global variables within a thread, use thread-local storage.

like image 104
user4815162342 Avatar answered Oct 01 '22 10:10

user4815162342


Since each thread has its own stack, it is much better if each thread allocates its own variables, unless you need to share data between threads. The pthread_key_* is used for data sharing.

Documentation and small examples at http://pubs.opengroup.org/onlinepubs/007904975/functions/pthread_key_create.html.

like image 26
epx Avatar answered Oct 01 '22 10:10

epx