Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, then are constructed when you first access them from a given thread.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading