How to initialize thread local variable in c++? [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-21 08:52:00

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/12075349/how-to-initialize-thread-local-variable-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!