中初始化线程局部变量

中初始化线程局部变量

本文介绍了如何在c ++中初始化线程局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用c ++ 11 thread_local 来创建和使用thread_local变量,但因为它不是但由gcc支持,我使用特定于gcc的 __ thread 。我声明变量的方式是:

$ $ $ $ $ $ $ $ $ $ $ $ $ b static __thread int64_t m_minInt;

};
__thread int64_t myClass :: m_minInt = 100;

当我编译它时,我收到一个错误,如$ /

 错误:'myClass :: minInt'是线程本地的,所以不能被动态初始化

如何正确做到这一点?



PS:gcc版本:4.6.3



  myClass 
=h2_lin>解决方案

{
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)//注意 - 这是(由于__thread)threadsafe
{
m_minIntInitialized = true;
m_minInt = 100;
}

return m_minInt;
}

m_minIntInitialized 有保证为零。

在大多数情况下(


I wanted to use the c++11 thread_local to create and use thread_local variable but as it is not yet supported by gcc, I am using gcc specific __thread. The way I declared the variable is

myClass
{
public:

  static __thread int64_t m_minInt;

};
__thread int64_t myClass::m_minInt = 100;

When I compile it, I get an error like

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

How to properly do it?

PS: gcc version: 4.6.3

解决方案

You need to use lazy initialization.

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 is guaranteed to be zero.

In most cases (ELF specification) it is placed to .tbss section, which is zero-initialized.

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

这篇关于如何在c ++中初始化线程局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:35