Anne Quinn
Anne Quinn

Reputation: 13020

How to construct a static thread_local member with non-trivial constructor

I have a class member I would like to construct that should be local to each thread that accesses it. The constructor requires a few arguments though, so I can't rely on static zero initialization.

class ThreadMem{
public:
    ThreadMem(uint32 cachelineSize, uint32 cachelineCount);
};    

class ThreadPool{
public:
    ThreadPool(uint32 cachelineSize, uint32 cachelineCount){
        // I need to prepare the `m_mem` in other threads with these arguments somehow
    }
    ThreadMem & mem() {
        return m_mem;
    }
private:
    static thread_local ThreadMem m_mem;
};

Where would be the best place to construct static thread_local ThreadMem ThreadPool::m_mem so that it's only constructed once per thread, with values only ThreadPool's constructing thread can calculate at runtime?

Upvotes: 2

Views: 1056

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136495

That static class member is constructed by C++ run-time at dynamic initialization phase before main is entered. The arguments to its constructor must be available by that time, which may be infeasible.

Upvotes: 1

Related Questions