Search code examples
cstacklock-freecircular-buffer

Circular buffer Vs. Lock free stack to implement a Free List


As I have been writing some multi-threaded code for fun, I came up with the following situation:

a thread claims a single resource unit from a memory pool, it processes it and sends a pointer to this data to another thread for further operation using a circular buffer (1R / 1W case).

The latter must inform the former thread whenever it is done with the data he received, so that the memory can be recycled.

I wonder whether it is better - performance-wise - to implement this "Freelist" as another circular buffer - holding the addresses of free resources - or choose the lock-free stack way (implementing DCAS on x86-64).

Generally speaking, what could be the pros and the cons of the two different approaches ?


Solution

  • Just in case, there is a difference between lock-free and wait-free. The former means there is no locking but the thread can still busy-spin not making any progress. The latter means that the thread always makes progress with no locking or busy-spinning.

    With one reader and one writer lock-free and wait-free FIFO circular buffer is trivial to implement.

    I hear that LIFO stack can also be made wait-free, but not so sure about FIFO list. And it sound like you need a queue here rather then a stack.