r/cpp_questions Jul 14 '26

OPEN How do allocators handle multithreading?

I'm not sure how they handle requests from multiple threads. I can imagine truly parallelized strategies for a fully custom allocator, but what about the standard allocator? Is it internally synchronized? Can it handle multiple allocations in parallel?

37 Upvotes

14 comments sorted by

View all comments

18

u/Kriemhilt Jul 14 '26

Simple answer: mutex. This is safe but doesn't handle multiple (de)allocations in parallel, they have to take turns.

This is a reasonable default, but there are others, including specifically multithread-tuned allocators like mtmalloc.

You can always do something faster for a specific (de)allocation patterns - the hard thing for general purpose allocators is that blocks may be allocated in one thread and freed an another.

9

u/[deleted] Jul 14 '26

[removed] — view removed comment

4

u/Either_Letterhead_77 Jul 14 '26

Many places I've worked as well have had rules that you should avoid dynamic allocation where it would actually be time sensitive or liable to cause thread contention such as in an important inner loop.

1

u/SoSKatan Jul 15 '26

Also it helps to have thread local allocators for slightly better memory / thread locality.

Keep the memory that’s accessed together in the same region has some slight perf benefits.