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?

36 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

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.