Search code examples
c++thread-local-storage

Thread_local cost of unused variable


Variables declared thread_local are unique for each thread. But do they consume memory if the function is not called?

Let's say I have a bunch of libraries that have thread_local variables in their functions. When I create a thread, are these variables going to be initialized even if I never call the functions that use them?

Example:

int lib1_foo()
{
    thread_local int a, b;
    // ...
}

int lib2_bar()
{
     thread_local BigObject c;
    // ...
}

int main()
{
    std::thread t([]() {
        // Do a, b, c consume memory?
        // Are they initialized? 
    )();
    t.join();
}

Solution

  • They certainly consume memory. cppreference has this to say (emphasis mine):

    thread storage duration: The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration.

    As for initialisation, it then goes on to say:

    See Non-local variables and Static local variables for details on initialization of objects with this storage duration.

    From which we get:

    All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins.

    And:

    Static local variables ... are initialized the first time control passes through their declaration (plus some extra verbiage which is worth reading).