问题
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