How to use mmap to allocate a memory in heap?

后端 未结 2 1740
旧巷少年郎
旧巷少年郎 2020-12-23 18:05

Just the question stated, how can I use mmap() to allocate a memory in heap? This is my only option because malloc() is not a reentrant function.

2条回答
  •  臣服心动
    2020-12-23 18:36

    Make a simple slab allocator


    Although allocating memory in a signal handler1 does seem like something best avoided, it certainly can be done.

    No, you can't directly use malloc(). If you want it to be in the heap then mmap won't work either.

    My suggestion is that you make a special-purpose slab allocator based on malloc.

    Decide exactly what size of object you want and preallocate some number of them. Allocate them initially with malloc() and save them for concurrent use later. There are intrinsically reentrant queue-and-un-queue functions that you can use to obtain and release these blocks. If they only need to be managed from the signal handler then even that isn't necessary.

    Problem solved!


    1. And if you are not doing that then it seems like you have an embedded system or could just use malloc().

提交回复
热议问题