Functions to use Thread Local Storage. More...
Macros | |
#define | TLS_MAX_KEYS 64 |
The maximum number of thread local storage variables. This number is process wide. | |
Functions | |
void ** | tls_address (int32 index) |
Retrieve the pointer that refers to the data of this thread at the provided index. | |
int32 | tls_allocate (void) |
Allocate a unique index to use for storing variables. | |
void * | tls_get (int32 index) |
Retrieve the data stored for this thread at the provided index. | |
void | tls_set (int32 index, void *value) |
Set the data of this thread at the provided index. | |
Functions to use Thread Local Storage.
The Thread Local Storage API provides convenient methods to transform global variables in to thread-context sensitive variables. Some applications rely on global variables as a way of intercommunicating between functions and objects, but one of your demands might be that the contents of that variable differs between threads.
The following example demonstrates how an imaginary thread manager that stores per thread data would function. The constructor of this ThreadManager
allocates the TLS variables using tls_allocate(). This only has to be done once, and not in every spawned thread! Then, every spawned thread that interacts with this thread manager, should call the InitThread()
function. This one associates the supplied thread data with the TLS index using tls_set(). Each thread can get their associated data with GetCurrentThreadData()
, which uses tls_get() to retrieve the associated thread data at the provided index.
gThreadName
and gThreadData
, are only indexes. You cannot use these variables to access data without the TLS API.#define TLS_MAX_KEYS 64 |
The maximum number of thread local storage variables. This number is process wide.
void ** tls_address | ( | int32 | index | ) |
Retrieve the pointer that refers to the data of this thread at the provided index.
You can use this pointer to directly manipulate your thread data.
index | The index that you retrieved with tls_allocate(). |
NULL
if the index is invalid.int32 tls_allocate | ( | void | ) |
Allocate a unique index to use for storing variables.
You should only have to do this once to allocate the global index, which you can reuse in every thread.
B_NO_MEMORY
.void * tls_get | ( | int32 | index | ) |
Retrieve the data stored for this thread at the provided index.
index | The index that you retrieved with tls_allocate(). |
NULL
if there is no data set, or the index is invalid.void tls_set | ( | int32 | index, |
void * | value | ||
) |
Set the data of this thread at the provided index.
It is up to you to make sure the index is valid. Any invalid indices can lead to unpredictable results.
index | The index that you retrieved with tls_allocate(). |
value | The data that should be associated with the index for this thread. |