mjansson / rpmalloc

Public domain cross platform lock free thread caching 16-byte aligned memory allocator implemented in C

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

rpmalloc_heap_free - thread safe?

rjobling opened this issue · comments

commented

I have a setup where we're using regular rpmalloc/rpfree calls for most regular allocations.

However, we have a lot of temporary allocations and so to keep those separate I've used a first class heap.

Since first class heaps are documented as not being thread safe I've wrapped those calls in a mutex. The efficiency is not paramount so this seems okay and seems to work.

It is however quite a burden that each call to rpfree or rpmalloc_heap_free has to match however the memory was allocated. So I was looking at how it might be possible to have one intelligent version of free that would handle all cases.

Investigating the code I realized that rpmalloc_heap_free isn't doing anything different from regular rpfree. And also that rpfree handles multi-threading by deferring frees made from threads other than the owner.

It seems plausible that I could just use rpfree for all frees and this will work because rpfree is thread safe.

Is this true and is this by design? If so it would be really nice to be able to just use rpfree in all cases and rely on that working in the future.

Sure, you can use rpfree for a block from a first class heap, but you must still make sure that only one thread calls it at any given time (the thread ownership test in the free path will just let any thread directly free from a first class heap) - so for a first class heap rpfree will NOT be thread safe.

The other option would be to promote the heap to be the current heap for a thread by using rpmalloc_heap_thread_set_current in which case it will be assigned to the caller thread and now thread safe. Note that you cannot 'unassign' a heap from a thread in this case.

The main use case for a first class heap is when you have a known lifetime of the heap and can do a single call to rpmalloc_heap_free_all to release all memory used in the heap.