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

后端 未结 4 655
一整个雨季
一整个雨季 2020-12-24 07:27

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.

相关标签:
4条回答
  • 2020-12-24 07:42

    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...

    0 讨论(0)
  • 2020-12-24 07:43

    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.

    0 讨论(0)
  • 2020-12-24 07:52

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

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

    0 讨论(0)
  • 2020-12-24 07:56

    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.

    0 讨论(0)
提交回复
热议问题