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 eac
Folly (Facebook Open-source Library) has a portable implementation of Thread Local Storage.
According its authors:
Improved thread local storage for non-trivial types (similar speed as
pthread_getspecific
but only consumes a singlepthread_key_t
, and 4x faster thanboost::thread_specific_ptr
).
If your looking for a portable implementation of Local Storage Thread, this library is a good option.
C++11 specifies a thread_local storage type, just use it.
AnotherClass::threadSpecificAction()
{
thread_local MyClass *instance = new MyClass();
instance->doSomething();
}
One optional optimization is to also allocate on thread local storage.
#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);
}
instance->doSomething();