Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 502
Janik Zikovsky Avatar asked Dec 24 '10 05:12

Janik Zikovsky


People also ask

Does malloc allocate heap memory?

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns.

Does malloc allocates memory in heap or stack?

All variables allocated by malloc (or new in C++) is stored in heap memory.

Does malloc use a lock?

So, malloc uses a lock to make the threads "take turns" accessing malloc's internal structures.

Does malloc increase heap size?

The first time, malloc creates a new space (the heap) for the program (by increasing the program break location).


1 Answers

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.

like image 193
Kirill V. Lyadvinsky Avatar answered Oct 07 '22 01:10

Kirill V. Lyadvinsky