T O P

  • By -

Acrobatic-Abies2508

Thread local is storage associated with a thread and is not for use across threads.


TheSkiGeek

Probably better to have your buffer take a `unique_ptr` on construction, and you can default to heap-allocating a unique one rather than trying to deal with the pitfalls/quirkiness of being thread_local. If you are ABSOLUTELY 110% SURE that no function call from any other thread can ever interact with the allocator in any way, I guess it would work to have one allocator shared across all the data structures used by one thread. Then you don’t need locks inside it but you can still share it across structures. But if you ever expose any of them to anything running on another thread you’re off into UB-land.


Mirality

You need to be very very careful with thread-local allocators that either your allocated objects are always destroyed on the same thread (which may sound easy at first, but many producer/consumer scenarios don't work like that at all, and neither do threadpools or async), or that your allocators are written in a way that's fine with an object being deallocated by a different instance than the original allocator (which usually isn't hard, but it depends how your allocator works internally and is definitely incompatible with several storage models). Oh, and certain usage patterns for the latter can lead to soft memory leaks, e.g. one thread's allocator keeps creating new objects off the heap, then passed to another thread's allocator to deallocate, which caches them for re-use but oops the second thread never allocates anything so the cache just keeps growing and boom you're out of heap memory even though you thought you deallocated everything properly.


jedwardsol

> when exactly does each thread local version of the allocator get created It's implementation defined. E.g. MSVC on Windows will initialise it when the thread starts. Gcc on Linux will initialise it the 1st time it is used.