How to have several different heaps in one thread
I use mi_heap_new to create several heaps in one thread, but I find that they actually share the same tld, indicating that they point to the same segments even though they are "different heaps".
My question is: how to allocate several different heaps within one thread that have different segments all?
- Explicit Segment Isolation: Ensure each heap is allocated from a different memory segment. The key is to avoid any unintended sharing of memory or thread-local data (TLD) between heaps. If mi_heap_new is creating heaps that share segments, you might need to configure the allocator to allocate from distinct segments. 2. Use the mi_heap_new Function Correctly: Normally, mi_heap_new() creates a new heap with its own internal memory management. If heaps are still sharing the same segments, the allocator might not be properly isolating the memory regions. Check if the heap initialization allows you to specify a segment or region for each heap.
Updated Code Example for Independent Heaps:
#include "mi_heap.h"
// Function to initialize and allocate memory for independent heaps
void create_independent_heaps() {
// Creating independent heaps
mi_heap_t* heap1 = mi_heap_new(); // Create first heap
mi_heap_t* heap2 = mi_heap_new(); // Create second heap
// Verify that heaps do not share memory or segments
void* ptr1 = mi_heap_malloc(heap1, 1024); // Allocate 1KB from heap1
void* ptr2 = mi_heap_malloc(heap2, 2048); // Allocate 2KB from heap2
// Ensure heaps do not share memory by performing operations
if (ptr1 && ptr2) {
printf("Memory allocated from independent heaps!\n");
}
// Free allocated memory
mi_heap_free(heap1, ptr1);
mi_heap_free(heap2, ptr2);
// Destroy the heaps
mi_heap_destroy(heap1);
mi_heap_destroy(heap2);
}
int main() {
create_independent_heaps();
return 0;
}
Key Considerations: • Different Segments: The memory allocator (MI) usually assigns different segments automatically for separate heaps. However, if it doesn’t, or if the default implementation is causing sharing of segments, consider checking the allocator’s documentation for any options to force heap segmentation isolation. This might be achieved via special configuration flags or APIs. • Thread-local Data (TLD): If mi_heap_new does not create separate heaps with distinct TLDs, it may be due to the thread-local data management in the library. Investigate whether the allocator has ways to manually assign separate TLDs for each heap. • Memory Allocation from Different Heaps: In the provided example, we allocate from two separate heaps (heap1 and heap2) and verify that they are independent by allocating different amounts of memory and freeing them separately. This should ensure that they are not sharing memory regions.