Thread Local Storage
The ILE C, ILE C++, and ILE RPG compilers all support thread local storage (TLS). The TLS variables for each program or service program are organized into a TLS frame. The TLS frame contains an initialized copy of each TLS variable that is associated with the program or service program. One copy of the TLS frame is created for each thread that runs the program or service program. For information about the support available in a particular compiler, refer to documentation of the specific high-level language (HLL).
A TLS variable is similar to a static variable, except that a unique copy of the TLS variable exists for each thread. See the following table for the differences between TLS variables and static variables.
| Static Variable | TLS Variable | |
|---|---|---|
| When is storage for the variable allocated? | When the program or service program is activated. | When the thread first touches the TLS frame that contains the variable. |
| When is the variable initialized? | When the program or service program is activated.2 | When the thread first touches the TLS frame that contains the variable. |
| When is storage for the variable freed? | When the program or service program is deactivated. | When the thread is destroyed. |
| Does each thread have its own copy of the variable? | No, a single copy is shared by all threads. | Yes. |
| Is the variable stored in single-level storage or teraspace storage? | Depends on the activation group of the program or service program.1 | TLS variables are always stored in teraspace storage.1 |
| 1 See Teraspace and Single-Level Storage for more information.
2 This represents the time when the variable is initialized directly by the system. The variable might be initialized indirectly by your HLL at a later time. |
||
When a reference is made to a TLS variable within a thread, the reference accesses the copy of the variable associated with that thread. It will not access or update a copy of the variable associated with any other thread.
Because each TLS variable is associated with one thread, synchronization (as described in Shared Storage Synchronization) is usually not a concern. Synchronization might become necessary, however, if the address of a TLS variable is passed to another thread.