g++ __thread = non-trivial constructor

拈花ヽ惹草 提交于 2019-12-11 13:34:04

问题


I'd like to use __thread modifier, as a substitution for thread_local from C++11, in g++. Unfortunately my local thread variable doesn't have trivial constructor (it has to set the value of one integer components). I think about using this kind of construction:

__thread MyVariable *var;

__thread MyVariable* MyClass::var = nullptr;

End every time I'd like to get an acces to var I check if it was allocated:

if(var == nullptr)
   var = new MyVariable(42);

But I have no idea, how to free allocated in this way memory.


回答1:


__thread storage specifier can not handle objects with non-trivial constructors and destructors.

For objects with non-trivial constructors and destructors you may like to use boost::thread_specfic_ptr<>. When a thread terminates boost::thread_specfic_ptr<> invokes delete on the corresponding thread-specific object.




回答2:


I've written a small demo program to show how to define a thread_local macro that works with non-trivial types and stores everything with __thread duration. It is superior to boost::thread_specific_ptr because it doesn't do any dynamic memory allocation.

See my answer to this question:

gcc 4.7 on linux pthreads - nontrivial thread_local workaround using __thread (no boost)



来源:https://stackoverflow.com/questions/9148640/g-thread-non-trivial-constructor

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