Does the typical malloc
(for x86-64 platform and Linux OS) naively lock a mutex at the beginning and release it when done, or does it lock a mutex in a more clever way at a finer level, so that lock contention is reduced? If it indeed does it the second way, how does it do it?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
glibc 2.15
operates multiple allocation arenas. Each arena has its own lock. When a thread needs to allocate memory,malloc()
picks an arena, locks it, and allocates memory from it.The mechanism for choosing an arena is somewhat elaborate and is aimed at reducing lock contention:
With this in mind,
malloc()
basically looks like this (edited for brevity):This allocator is called
ptmalloc
. It is based on earlier work by Doug Lea, and is maintained by Wolfram Gloger.Doug Lea's
malloc
used coarse locking (or no locking, depending on the configuration settings), where every call tomalloc
/realloc
/free
is protected by a global mutex. This is safe but can be inefficient in highly multithreaded environments.ptmalloc3
, which is the defaultmalloc
implementation in the GNU C library (libc) used on most Linux systems these days, has a more fine-grained strategy, as described in aix's answer, which allows multiple threads to concurrently allocate memory safely.nedmalloc
is another independent implementation which claims even better multithreaded performance thanptmalloc3
and various other allocators. I don't know how it works, and there doesn't seem to be any obvious documentation, so you'll have to check the source code to see how it works.