WilliamKF WilliamKF - 1 year ago 106
Linux Question

How to allocate thread local storage?

I have a variable in my function that is static, but I would like it to be static on a per thread basis.

How can I allocate the memory for my C++ class such that each thread has its own copy of the class instance?

// How to allocate this with thread local storage?
static MyClass *instance = new MyClass();


This is on Linux. I'm not using C++0x and this is gcc v3.4.6.

Answer Source
#include <boost/thread/tss.hpp>
static boost::thread_specific_ptr< MyClass> instance;
if( ! instance.get() ) {
    // first time called by this thread
    // construct test element to be used in all subsequent calls from this thread
    instance.reset( new MyClass);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download