Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a thread local static in a template

How can I define a static member variable that is also thread local inside a template class? I think I've figured out how to do it in GCC, but would like to confirm this will work correctly in terms of linking, initialization and resolution. Also the translation to another compiler would be helpful (like MSVC) so I can get a nice macro to do this.

template<typename T>
class my_class
{
  struct some_type { };
  static __thread some_type * ptr;
};

template<typename T>
__thread typename my_class<T>::some_type * my_class<T>::ptr = 0;

An alternate way to achieve the same thing would also be okay (that is, to use a distinct thread local per template instance).

like image 960
edA-qa mort-ora-y Avatar asked Nov 20 '10 05:11

edA-qa mort-ora-y


1 Answers

I believe your code is correct, and would translate in MSVC by replacing __thread by __declspec(thread) (see Thread Local Storage on MSDN) :

template<typename T>
class my_class
{
  struct some_type { };
  static __declspec(thread) some_type * ptr;
};

template<typename T>
__declspec(thread) typename my_class<T>::some_type * my_class<T>::ptr = 0;
like image 197
icecrime Avatar answered Oct 21 '22 22:10

icecrime