C++11: Nontrivial Thread Local Static Variable? C++11: Nontrivial Thread Local Static Variable? multithreading multithreading

C++11: Nontrivial Thread Local Static Variable?


The Standard describes thread_local as a storage specifier like the others (static, extern etc.) in ยง7.1.1. There is no restriction to "simple" data types by any definition of that word.

The problem is briefly discussed in a pre-C++11 discussion document N2147 (see the section "Thread Variable Dynamic Initialization"). That includes a description of the key problems involved in the proper implementation. Apparently the GCC implementation (static __thread) hasn't solved these problems yet (which is consistent with the fact that GCC does not officially support C++11 thread_local).

One alternative is boost::thread_specfic_ptr<> mentioned in this earlier post and described here.

Another alternative is to use a std::thread object to implement the thread and ensure each instance maintains its own copy of the variable, possibly wrapped in a unique_ptr.


thread_local and __thread are, in fact, not the same thing. The main difference between them is precisely the one you stumbled upon - thread_local allows the variable to be non-POD. Unfortunately, this also has performance implications. See this question for more details about those performance implications.