How to allocate 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();
It is worth noting that C++11 introduces the thread_local
keyword.
Here is an example from Storage duration specifiers:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
thread_local unsigned int rage = 1;
std::mutex cout_mutex;
void increase_rage(const std::string& thread_name)
{
++rage;
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}
int main()
{
std::thread a(increase_rage, "a"), b(increase_rage, "b");
increase_rage("main");
a.join();
b.join();
return 0;
}
Possible output:
Rage counter for a: 2
Rage counter for main: 2
Rage counter for b: 2
boost::thread_specific_ptr
is the best way as it portable solution.
On Linux & GCC you may use __thread
modifier.
So your instance variable will look like:
static __thread MyClass *instance = new MyClass();