Is there any way to fully emulate thread_local usi

2019-02-18 01:50发布

问题:

The C++11 standard contains a new addition - the thread_local specifier - which makes static variables thread-local. The standard thread_local supports non-trivial types - those with constructors and destructors. GCC unfortunately supports only trivial types via __thread specifier provided as extension. Is there's a way to emulate thread_local on top of __thread? The implementation of __thread is very fast (equivalent to regular variable plus two indirections), so I want to avoid library functions in the hot path.

I'm using GCC and Linux. Portability is not required.

回答1:

no.

gcc does currently not have the ability to run ctor/dtor for __thread stuff on thread creation/destruction, so unless you dont need ctor/dtor to run (in which case __thread is exactly what you need, and nothing to emulate on top of it is needed), there is nothing yet that works like thread_local.

If however you can live with lazy initialization (like__thread T* ptr; if(!ptr){...}) you can hack something together with pthread_key_create where you can register a destruction function that will be run at thread destruction, and then you can register all your pointers there.

Or you can use boost::thread_specific_ptr which more or less does this (possibly without using the __thread TLS as underlying implementation detail)