In multithreaded C/C++, does malloc/new lock the heap when allocating memory

10,796

Solution 1

There could be improvements in certain implementations, such as creating a thread-specific cache (in this case allocations of small blocks will be lock-free). For instance, this from Google. But in general, yes, there is a lock on memory allocations.

Solution 2

By default Windows locks the heap when you use the Win API heap functions.

You can control the locking at least at the time of heap creation. Different compilers and C runtimes do different things with the malloc/free family. For example, the SmartHeap API at one point created one heap per thread and therefore needed no locking. There were also config options to turn that behavior on and off.

At one point in the early/mid '90s the Borland Windows and OS/2 compilers explicitly turned off Heap locking (a premature optimization bug) until multiple threads were launched with beginthread. Many many people tried to spawn threads with an OS API call and then were surprised when the heap corrupted itself all to hell...

Solution 3

http://en.wikipedia.org/wiki/Malloc

Modern malloc implementations try to be as lock-free as possible by keeping separate "arenas" for each thread.

Solution 4

Free store is a shared resource and must be synchronized. Allocation/deallocation is costly. If you are multithreading for performance, then frequent allocation/deallocation can become a bottleneck. As a general rule, avoid allocation/deallocation inside tight loops. Another problem is false sharing.

Share:
10,796
Janik Zikovsky
Author by

Janik Zikovsky

Updated on June 15, 2022

Comments

  • Janik Zikovsky
    Janik Zikovsky almost 2 years

    I'm curious as to whether there is a lock on memory allocation if two threads simultaneously request to allocate memory. I am using OpenMP to do multithreading, C++ code.

    OS's: mostly linux, but would like to know for Windows and Mac as well.