Thread-Local Storage

From SEGGER Wiki
Revision as of 11:17, 17 May 2022 by Johannes (talk | contribs) (Created page with "Thread-Local Storage (TLS) enables the use of local and global variables to be unique to a thread. The most popular thread-local variable is `errno`. == Thread-local variable...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Thread-Local Storage (TLS) enables the use of local and global variables to be unique to a thread. The most popular thread-local variable is `errno`.

Thread-local variables in the standard library

C standard libraries can support usage of thread-local storage.

Library objects that need thread-local storage when used in multiple tasks are for example:

  • error functions - errno, strerror.
  • locale functions - localeconv, setlocale.
  • time functions - asctime, localtime, gmtime, mktime.
  • multibyte functions - mbrlen, mbrtowc, mbsrtowc, mbtowc, wcrtomb, wcsrtomb, wctomb.
  • rand functions - rand, srand.
  • etc functions - atexit, strtok.
  • C++ exception engine.

Handling thread-local storage

To use thread-local storage it needs to be enabled and handled by the OS. If TLS is not enabled, most systems will treat thread-local variables like regular variables and share them across the whole system.

embOS

embOS is prepared to support TLS, but does not enable it per default. This has the advantage of no additional overhead as long as TLS is not needed by the application. The embOS implementation of thread-local storage allows activation of TLS separately for every task. Only tasks that call functions using TLS need to activate it by calling an initialization function when the task is started.

Linker configuration

Thread-local data and thread-local bss need to be placed in memory in a block and order which is known to the OS. The OS creates a copy of the block for each thread or task and on access of a thread-local variable points to the block copy belonging to the active thread.

SEGGER Linker

With the SEGGER Linker thread-local data and thread-local bss can be put into a block, which can then be placed regularly in RAM.

  define block tls with fixed order { block tbss, block tdata };
  
  place in RAM with auto order      { block tls, readwrite, zeroinit };

Linker warning "thread-local and non-thread-local sections cannot be mixed"

When the tls block is declared without a specific ordering, the SEGGER Linker uses auto order to reduce the loss due to alignment and may interfere with the ordering expected by the OS.

To resolve this warning, define the block which contains tbss and tdata with fixed order.