I am looking for a ring buffer implementation (or pseudocode) in C with the following characteristics:
- multiple producer single consumer pattern (MPSC)
- consumer blocks on empty
- producers block on full
- lock-free (I expect high contention)
So far I’ve been working only with SPSC buffers – one per producer – but I would like to avoid the continuous spinning of the consumer to check for new data over all its input buffers (and maybe to get rid of some marshaling threads in my system).
I develop for Linux on Intel machines.
I think I have what you are looking for. It is a lock free ring buffer implementation that blocks producer/consumer. You only need access to atomic primitives – in this example I will use gcc’s
syncfunctions.It has a known bug – if you overflow the buffer by more than 100% it is not guaranteed that the queue remains FIFO (it will still process them all eventually).
This implementation relies on reading/writing the buffer elements as being an atomic operation (which is pretty much guaranteed for pointers)