Is there any way to fully emulate thread_local using GCC's __thread?

混江龙づ霸主 提交于 2019-12-19 08:29:28

问题


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)



来源:https://stackoverflow.com/questions/12063073/is-there-any-way-to-fully-emulate-thread-local-using-gccs-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!