g++ __thread = 重要的构造函数
我想在 g++ 中使用 __thread 修饰符来替代 C++11 中的 thread_local。不幸的是,我的本地线程变量没有简单的构造函数(它必须设置一个整数分量的值)。 我考虑使用这种结构:
__thread MyVariable *var;
__thread MyVariable* MyClass::var = nullptr;
每次我想访问 var 时都会结束我检查它是否已分配:
if(var == nullptr)
var = new MyVariable(42);
但我不知道如何释放以这种方式分配的内存。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
__thread
存储说明符无法处理具有重要构造函数和析构函数的对象。对于具有重要构造函数和析构函数的对象,您可能喜欢使用
boost::thread_specfic_ptr
。当线程终止时,boost::thread_specfic_ptr
会在相应的线程特定对象上调用delete
。__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 terminatesboost::thread_specfic_ptr<>
invokesdelete
on the corresponding thread-specific object.我编写了一个小型演示程序来展示如何定义一个 thread_local 宏,该宏适用于非平凡类型并存储具有 __thread 持续时间的所有内容。它优于 boost::thread_specific_ptr 因为它不执行任何动态内存分配。
请参阅我对此问题的回答:
Linux pthreads 上的 gcc 4.7 - 使用 __thread 的非平凡 thread_local 解决方法(无提升)
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)