g++ __thread = 重要的构造函数

发布于 2025-01-02 19:28:22 字数 342 浏览 2 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱本泡沫多脆弱 2025-01-09 19:28:22

__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 terminates boost::thread_specfic_ptr<> invokes delete on the corresponding thread-specific object.

意中人 2025-01-09 19:28:22

我编写了一个小型演示程序来展示如何定义一个 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文