【问题标题】:g++ __thread = non-trivial constructorg++ __thread = 非平凡的构造函数
【发布时间】:2012-02-05 10:53:36
【问题描述】:

我想在 g++ 中使用 __thread 修饰符来替代 C++11 中的 thread_local。不幸的是,我的本地线程变量没有简单的构造函数(它必须设置一个整数分量的值)。 我考虑使用这种结构:

__thread MyVariable *var;

__thread MyVariable* MyClass::var = nullptr;

每次我想获得对 var 的访问权时,我都会检查它是否已分配:

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

但我不知道如何释放以这种方式分配的内存。

【问题讨论】:

  • delete 在你的线程生命周期结束时。

标签: c++ multithreading gcc g++


【解决方案1】:

__thread 存储说明符无法处理具有非平凡构造函数和析构函数的对象。

对于具有重要构造函数和析构函数的对象,您可能喜欢使用boost::thread_specfic_ptr<>。当线程终止时,boost::thread_specfic_ptr<> 会在相应的线程特定对象上调用 delete

【讨论】:

  • 不幸的是,我不能在一个类中使用 boost::thread_specific_ptr,它将被传递给 std::thread。 pastebin.com/vckyqLME
  • boost::thread_specfic_ptr<> 是不可复制的,但是,Run 的实例在传递给 thread 构造函数时会被复制。
  • 解释您尝试使用线程特定存储解决的问题。您发布的示例代码没有提供足够的上下文。
【解决方案2】:

我编写了一个小型演示程序来展示如何定义一个 thread_local 宏,该宏适用于非平凡的类型并以 __thread 持续时间存储所有内容。它优于 boost::thread_specific_ptr 因为它不做任何动态内存分配。

查看我对这个问题的回答:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2015-08-10
    • 2018-10-28
    • 2022-01-08
    相关资源
    最近更新 更多