【问题标题】:How to initialize thread local variable in c++? [duplicate]如何在 C++ 中初始化线程局部变量? [复制]
【发布时间】:2012-08-18 00:11:28
【问题描述】:

可能重复:
C++11 thread_local in gcc - alternatives
Is there any way to fully emulate thread_local using GCC's __thread?

我想使用 c++11 thread_local 来创建和使用 thread_local 变量,但由于 gcc 尚不支持它,我正在使用 gcc 特定的 __thread。我声明变量的方式是

myClass
{
public:

  static __thread int64_t m_minInt;

};
__thread int64_t myClass::m_minInt = 100;

当我编译它时,我得到一个类似

的错误
error: ‘myClass::minInt’ is thread-local and so cannot be dynamically initialized

如何正确做?

PS:gcc 版本:4.6.3

【问题讨论】:

  • @betabandido 您链接的问题讨论了 c++11 中 thread_local 的替代方案。我的问题是如何使用 gcc 中的 __thread 。特别是有问题的错误消息。我试图在别处找到它,但找不到它。谢谢。

标签: c++ multithreading gcc thread-local thread-local-storage


【解决方案1】:

你需要使用延迟初始化。

myClass
{
public:

  static __thread int64_t m_minInt;
  static __thread bool m_minIntInitialized;

  static int64_t getMinInt();
};
__thread int64_t myClass::m_minInt;
__thread bool myClass::m_minIntInitialized;


int64_t myClass::getMinInt()
{
  if (!m_minIntInitialized)  // note - this is (due to __thread) threadsafe
  {
    m_minIntInitialized = true;
    m_minInt = 100;
  }

  return m_minInt;
}

m_minIntInitialized 保证为零。

在大多数情况下 (ELF specification),它被放置到零初始化的 .tbss 部分。

对于 C++ - http://en.cppreference.com/w/cpp/language/initialization

对于所有其他非局部静态和线程局部变量,零 初始化发生。在实践中,变量将 被零初始化的被放置在程序的 .bss 段中 图像,不占用磁盘空间,被操作系统清零 加载程序时。

【讨论】:

  • 你怎么知道 m_minIntInitialized 最初是假的?
  • @CygnusX1,我已经更新了答案。
  • 你有一个竞争条件:其他线程可以在标志设置为 true 之后但在变量初始化之前读取 m_minInt;
  • @gdy,其他线程怎么可能干扰线程局部变量?
  • @Yossarian,哦,对了
猜你喜欢
  • 2017-05-14
  • 2018-09-23
  • 2011-12-27
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多