The GNU C Library implements functions to provide thread-local storage, a mechanism by which variables can be defined to have unique per-thread storage, lifetimes that match the thread lifetime, and destructors that cleanup the unique per-thread storage.
Several data types and macros exist for working with thread-local storage:
The
tss_tdata type identifies a thread-specific storage object. Even if shared, every thread will have its own instance of the variable, with different values.
The
tss_dtor_tis a function pointer of typevoid (*) (void *), to be used as a thread-specific storage destructor. The function will be called when the current thread callsthrd_exit(but never when callingtss_deleteorexit).
thread_localis used to mark a variable with thread storage duration, which means it is created when the thread starts and cleaned up when the thread ends.Note: For C++, C++11 or later is required to use the
thread_localkeyword.
TSS_DTOR_ITERATIONSis an integer constant expression representing the maximum number of iterations over all thread-local destructors at the time of thread termination. This value provides a bounded limit to the destruction of thread-local storage; e.g., consider a destructor that creates more thread-local storage.
The following functions are used to manage thread-local storage:
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
tss_createcreates a new thread-specific storage key and stores it in the object pointed to by tss_key. Although the same key value may be used by different threads, the values bound to the key bytss_setare maintained on a per-thread basis and persist for the life of the calling thread.If
destructoris not NULL, a destructor function will be set, and called when the thread finishes its execution by callingthrd_exit.This function returns
thrd_successiftss_keyis successfully set to a unique value for the thread; otherwise,thrd_erroris returned and the value oftss_keyis undefined.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
tss_setsets the value of the thread-specific storage identified by tss_key for the current thread to val. Different threads may set different values to the same key.This function returns either
thrd_successorthrd_error.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
tss_getreturns the value identified by tss_key held in thread-specific storage for the current thread. Different threads may get different values identified by the same key. On failure,tss_getreturns zero.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
tss_deletedestroys the thread-specific storage identified by tss_key.