I was recently using an object whose purpose is to allocate and deallocate memory as a singleton. Something like
class MyValue
{
// ...
static Allocator& GetAllocator()
{
static Allocator allocator;
return allocator;
}
// ...
};
I realized later Allocator
is not thread-safe: when multiple threads were using the same allocator concurrently, occasionally strange things were happening, causing assertions and segmentation faults.
Solution: use different allocators for different threads:
class MyValue
{
// ...
static Allocator& GetAllocator()
{
thread_local static Allocator allocator;
return allocator;
}
// ...
};
Awesome! My problems are gone! Just one question: Will my allocator variable be initialized every time a thread is created, even if the majority of threads won't use this variable?
The initialization of the allocator might be heavy operation, so I would like it to be initialized only when it is actually required, not in every thread.
I read that thread_local
variables are allocated by each thread. Does that mean they are also constructed? And does this allocation (or construction) happen systematically for each thread that is created or just for threads that use it?
I faintly remember hearing in a course that most details about threads and thread-local storage are platform dependent. If this is the case, I'm particularly interested in Linux and FreeBSD.
Related (interesting reads, but I could not find the answer there):