This is the general idea but:

  * Value can't be a ref object, it has to be an object or ptr object for 
manual memory management and you can do ref counting by leveraging Nim 
destructors as I do here: 
<https://github.com/mratsim/weave/blob/2e528bd2/weave/cross_thread_com/flow_events.nim#L176-L201>
 (you don't need the atomic load, fence, fetchSub in a single threaded context 
so adapt it)
  * If your pool is a global that has the same lifetime as the application and 
you have a bounded size, use manual memory management for it, here you have 
extra pointer indirection, you allocate a seq of ref. Instead just allocate a 
`ptr UncheckedArray[Value]`. This would ensure that all values are contiguous 
as well and limit memory fragmentation.
  * If your pool need variable size, this becomes more complicated but usually 
you can always have a maximum bounds otherwise use a linked list of fixed size 
pools.



* * *

Actual code

This is a very simple bounded object pool you can draw inspiration from 
<https://github.com/mratsim/weave/blob/v0.4.0/weave/memory/persistacks.nim#L14-L124>.
 It does not support multiple owners and so no refcounting scheme is needed.

This allows multiple owners via refcounting: 
<https://github.com/mratsim/weave/blob/2e528bd2a6a04306fd029f04a0af87fa201e5d89/weave/cross_thread_com/flow_events.nim#L176-L201>

This allows dynamic allocations of pools (though most of the code is related to 
dealing with thread-safety): 
<https://github.com/mratsim/weave/blob/ce8cac849b1c21b92a8b41cf52dc51c8b959a053/weave/memory/memory_pools.nim#L232-L259>

Reply via email to