c++thread-local-storage

Counting threads using thread_local


I wrote a following class:

#include <atomic>
#include <mutex>

class ThreadCounter
{
    static inline std::atomic<std::size_t> thread_count = 0;
    static thread_local ThreadCounter instance;

    ThreadCounter()
    {
        ++thread_count;
    }
    ~ThreadCounter()
    {
        --thread_count;
    }

public:
    static size_t get()
    {
        return thread_count;
    }
};

#include <iostream>

int main()
{
    std::cout << ThreadCounter::get() << std::endl;
}

I expect it to print 1, but I see 0.

I assumed that for each thread started, the instance would be constructed (I was quite certain because I observed such behavior some time ago in another case) and increment the counter. However, the value returned is always zero.

I also tried putting the instance outside of the class, both with static t_l and t_l-only specifiers, both in the header and in a separate .cpp file. None of these worked.

Is there some trick to make it work, or is this approach impossible?


Solution

  • thread_local variables are weird.

    Global thread_local variables are not constructed when you start a thread. Rather, they are constructed when you first access them from a given thread.

    You don't access instance anywhere, so it's not constructed.