How to initialize thread local variable in c++?

polapts picture polapts · Aug 22, 2012 · Viewed 10.6k times · Source

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

Answer

nothrow picture nothrow · Aug 22, 2012

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.