Thread Local Storage (TLS)

QNX SDP8.0System ArchitectureDeveloperUser
In multithreaded processes, all of the threads in the process share the same static and global variables. Thread local storage (TLS) allows each thread in a process to store its own copy of static or global memory. When using TLS, memory for the unique data is allocated when the thread starts and deallocated when it ends. Any pointers to variables in threads using TLS become invalid when the thread ends. You can declare the following keywords with a variable to provide it with TLS duration:
  • _Thread_local (in C11 and later)
  • thread_local (in C++11 and later)
  • __thread (a GCC extension)
Note:
  • In C11 and later, the <threads.h> header file defines thread_local as a macro to use as an alias for the _Thread_local keyword.
  • For better code portability, avoid using the __thread keyword, as it's a GCC extension and may not be supported on all systems.
You can set these keywords with the following variable types:
  • global
  • file-scoped static
  • function-scoped static
However, you can't set them on block-scoped automatic, or non-static data members. These keywords can be used in library code and the executable. For example, use the thread_local keyword to declare a global variable:
thread_local unsigned global_x;
Use the thread_local keyword to declare a file-scoped static variable:
static thread_local unsigned file_x;
Use the thread_local keyword to declare a function-scoped static variable:
unsigned update_thread_count(unsigned value) {
    static thread_local unsigned count;
    count += value; /* Each thread will have its own value for count */
    return count;
}

TLS functionality isn't equivalent to using thread-specific calls, such as pthread_setspecific(), which use thread-specific data instead. These calls are less efficient in the way that they store and access data. Thread-specific calls take more work to set up because a combination of these calls is required for every thread that needs data. For more information on thread-specific data, refer to the "Thread attributes" page.

Page updated: