0

I want to create a custom allocator for a multimap that will allocate the elements in shared memory.I came across boost.interprocess but found it quite complicated to implement.Is there any other workaround ?

  • Possible duplicate of https://stackoverflow.com/questions/11373796/custom-memory-allocator-for-stl-map – xeco Jun 26 '19 at 13:32
  • 4
    Possible duplicate of [Custom Memory Allocator for STL map](https://stackoverflow.com/questions/11373796/custom-memory-allocator-for-stl-map) – xeco Jun 26 '19 at 13:33

1 Answers1

-1

I will not give here any implementation, rather to give you some directions. If your shared memory abstraction or region, for example start at adress void* shMemAddr and if you decide that your stl container to use shared memory, what needs to be done is to make container allocate memory starting at shMemAddr and further, until there is available memory to allocate in your shared pool. You can implement that using any allocation strategy, for example using malloc or placement new. Further, to be available for your container to use your allocator you need to provide your allocator as template argument, for multimap it would be multimap::allocator_type class Alloc = allocator > as fourth template argument, after less as compare function,and, for example, if you store in your multimap pairs of int,double as key,value pairs, it would likely be something like this

multimap<int,double,less<int>,CustomAlloc<pair<int,double>>>

Now, your CustomAlloc allocator need to satisfies concept of Allocators which encapsulate specific lowlevel memory management, especially, if shared memory is resource to be allocate in, you need to arrange proper allocation of memory in a multithreaded enviornment. That means that, first, you need some structure for evidence of used memory. It can be some chained data structure, for example, and implementations like that is pretty common, so you need to keep invariants of that structure consistent. What that means is if your structure for book keeping of used(or free) memory need to be updated after succesfull allocation or deallocation it needs to be done atomicaly, so thread which possibly try to allocate memory see only structure in states before CustomAllocator allocation job is started or after allocation job is finished. For example, your first choice to do that could be using mutex to protect data, avoid races and keep invariants. This is just directions, and considering write your own allocators is not very hard, I hope this will help as good starting point.

Boki
  • 637
  • 3
  • 12