1.. _thread_local_storage: 2 3Thread Local Storage (TLS) 4########################## 5 6Thread Local Storage (TLS) allows variables to be allocated on a per-thread 7basis. These variables are stored in the thread stack which means every 8thread has its own copy of these variables. 9 10Zephyr currently requires toolchain support for TLS. 11 12 13Configuration 14************* 15 16To enable thread local storage in Zephyr, :kconfig:option:`CONFIG_THREAD_LOCAL_STORAGE` 17needs to be enabled. Note that this option may not be available if 18the architecture or the SoC does not have the hidden option 19:kconfig:option:`CONFIG_ARCH_HAS_THREAD_LOCAL_STORAGE` enabled, which means 20the architecture or the SoC does not have the necessary code to support 21thread local storage and/or the toolchain does not support TLS. 22 23:kconfig:option:`CONFIG_ERRNO_IN_TLS` can be enabled together with 24:kconfig:option:`CONFIG_ERRNO` to let the variable ``errno`` be a thread local 25variable. This allows user threads to access the value of ``errno`` without 26making a system call. 27 28 29Declaring and Using Thread Local Variables 30****************************************** 31 32The keyword ``__thread`` can be used to declare thread local variables. 33 34For example, to declare a thread local variable in header files: 35 36.. code-block:: c 37 38 extern __thread int i; 39 40And to declare the actual variable in source files: 41 42.. code-block:: c 43 44 __thread int i; 45 46Keyword ``static`` can also be used to limit the variable within a source file: 47 48.. code-block:: c 49 50 static __thread int j; 51 52Using the thread local variable is the same as using other variable, for example: 53 54.. code-block:: c 55 56 void testing(void) { 57 i = 10; 58 } 59