如何在c ++中初始化线程局部变量?

pol*_*pts 9 c++ multithreading gcc thread-local thread-local-storage

可能重复:
gcc中的C++ 11 thread_local - 替代方法
有没有办法使用GCC的__thread完全模拟thread_local?

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

myClass
{
public:

  static __thread int64_t m_minInt;

};
__thread int64_t myClass::m_minInt = 100;
Run Code Online (Sandbox Code Playgroud)

当我编译它时,我得到一个错误

error: ‘myClass::minInt’ is thread-local and so cannot be dynamically initialized
Run Code Online (Sandbox Code Playgroud)

如何正确地做到这一点?

PS:gcc版本:4.6.3

not*_*row 6

您需要使用延迟初始化.

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;
}
Run Code Online (Sandbox Code Playgroud)

m_minIntInitialized 保证为零.

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

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

对于所有其他非本地静态和线程局部变量,将进行零初始化.实际上,将初始化为零的变量放在程序映像的.bss段中,该段在磁盘上不占用空间,并在加载程序时由操作系统清零.

  • 你怎么知道m_minIntInitialized最初是假的? (7认同)
  • @ CygnusX1,我已经更新了答案. (2认同)
  • @gdy,其他线程如何可能干扰线程局部变量? (2认同)