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

后端 未结 4 673
一整个雨季
一整个雨季 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...

提交回复
热议问题