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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With