Cross-Platform C++

ot
class ThreadLocal

#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

 ThreadLocal()
Default constructor. Uses the operating-system's threading library to allocate a new thread-local variable.

The value of the variable is automatically initialized to zero for every thread.


~ThreadLocal

 ~ThreadLocal()
Destructor. Frees the thread-local variable, making it inaccessible from any thread.


Method Detail

get

void* get() const
Returns the current value of this ThreadLocal variable for the current thread.

See also:
set()

set

void set(void* value) const
Sets the value of this ThreadLocal for the currently executing thread.

Parameters:
value - the value to set this ThreadLocal variable to for the current thread
See also:
get()


Cross-Platform C++

Found a bug or missing feature? Please email us at support@elcel.com

Copyright © 2000-2003 ElCel Technology   Trademark Acknowledgements