|
OpenTop 1.3 | |||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | Cross-Platform C++ | ||||
SUMMARY: CONSTRUCTOR | METHOD | DETAIL: CONSTRUCTOR | METHOD |
#include "ot/base/ThreadLocal.h"
Provides a class interface to native thread-local storage which provides each thread with its own copy of a variable.
Each thread's copy of a ThreadLocal variable is initially set to zero.The variable type is a void pointer that can be used to hold a pointer or it can be cast to a long integer value.
In order for a ThreadLocal variable to be available to all threads, it is often convenient for instances of ThreadLocal to be created statically during program initialization. In this way the variable exists for the lifetime of the application, and any thread can access its individual value at any time.
In the following example, a static ThreadLocal variable is used to hold a pointer to an instance of an imaginary class WorkerThreadInfo. In this case, if the current thread does not have an instance of WorkerThreadInfo then it creates one and stores the pointer for subsequent use.
static ThreadLocal ThreadInfoPointer; WorkerThreadInfo* getThreadInfo() { WorkerThreadInfo* pInfo = ThreadInfoPointer.get(); if(!pInfo) { pInfo = new WorkerThreadInfo(Thread::CurrentThreadId()); ThreadInfoPointer.set(pInfo); } return pInfo; }
Note that the above example contains a potential memory leak. When a thread terminates, the ThreadLocal variable for that particular thread becomes inaccessible. If the variable contains a pointer to allocated memory then the memory is not automatically freed. For this reason it is a good idea to put any necessary clean-up code into the Runnable::run() method.
Constructor/Destructor Summary | |
ThreadLocal() Default constructor. | |
~ThreadLocal() Destructor. |
Method Summary | |
void* |
get() const Returns the current value of this ThreadLocal variable for the current thread. |
void |
set(void* value) const Sets the value of this ThreadLocal for the currently executing thread. |
Constructor/Destructor Detail |
ThreadLocal()
The value of the variable is automatically initialized to zero for every thread.
~ThreadLocal()
Method Detail |
void* get() const
void set(void* value) const
value
-
|
OpenTop 1.3 | |||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | Cross-Platform C++ | ||||
SUMMARY: CONSTRUCTOR | METHOD | DETAIL: CONSTRUCTOR | METHOD |