如何在c ++中初始化线程局部变量? [英] How to initialize thread local variable in c++?

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

问题描述


可能存在重复:

C ++ 11 thread_local in gcc - alternatives


我想用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 有保证为零。

在大多数情况下( ELF规范 a>)它被放置到.tbss节,该节已被初始化。



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


对于所有其他非本地静态和线程局部变量,将执行Zero
初始化。在实践中,将变为零初始化的变量放置在程序
图像的.bss段中,该段在磁盘上不占用空间,并且被OS
清零当加载程序。



Possible Duplicate:
C++11 thread_local in gcc - alternatives
Is there any way to fully emulate thread_local using GCC's __thread?

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

For all other non-local static and thread-local variables, Zero initialization takes place. In practice, variables that are going to be zero-initialized are placed in the .bss segment of the program image, which occupies no space on disk, and is zeroed out by the OS when loading the program.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆