How to initialize thread local variable in c++?

11,511

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.

Share:
11,511
polapts
Author by

polapts

Updated on July 20, 2022

Comments

  • polapts
    polapts almost 2 years

    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

    • polapts
      polapts over 11 years
      @betabandido the question you linked discusses the alternative to thread_local in c++11. My question is how to use __thread from gcc. Specifically the error message in question. I tried to find it elsewhere but could not get it. Thanks.
  • CygnusX1
    CygnusX1 over 10 years
    How do you know m_minIntInitialized is initially false?
  • nothrow
    nothrow over 8 years
    @CygnusX1, I've updated the answer.
  • denis
    denis about 8 years
    You have a race condition: other thread can read m_minInt after the flag is set to true but before the variable is initialized;
  • nothrow
    nothrow about 8 years
    @gdy, how can possibly other thread interfere with thread local variable?
  • denis
    denis about 8 years
    @Yossarian, oh, right