In glibc, malloc
is implemented with arenas.
So, for example, it is possible that the memory first allocated by malloc
and later free
d in thread A can not be used by another call of malloc
in thread B, since thread A and B may be in different arenas, and different arenas maintain different heaps and free lists of memory.
When it comes to C++ (maybe also C++11 since C++11 has a new standard), is the story still the same?
Or different threads actually share the same segment of heap and free list of memory, and new
in one thread can allocate the memory first new
ed and later delete
d by another thread?
If the answer is implementation dependent, then the question is how are they implemented in the major C++ compilers, such as g++, MVC++, icc?
EDIT
I think this question is valid in the sense that sometimes you launch many threads and in each thread you dynamically allocate/deallocate a big chunk of memory for a large number of objects, and you don't want the memory usage by your application to go ridiculously high.
The memory allocated in your process's address space will be contiguous. How those bytes are mapped into physical memory is implementation-specific; if you allocate a very large block of memory, it is likely to be mapped to different parts of physical memory.
Operator new can fail In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).
Given that threads occupy maximum amount of allocated memory right when it is created, as an application developer you can do the following to optimize your application's memory consumption: Create only *necessary* threads for your application.
By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as an argument for new, and it returns a null pointer instead.
This:
different threads actually share the same segment of heap and free list of memory, and new in one thread can allocate the memory first newed and later deleted by another thread
Purpose of the threads - share memory space. If you needn't this feature, you better use processes.
C++ std and the allocator implementation you use are two different things.. If you use gcc to compile your C++ code, it by default uses glibc as the allocator. So if your gcc is a sufficiently newer version, it uses glibc with per-thread arenas and you are good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With