Blog

Circular (ring) buffer plus neat virtual memory mapping trick

I’ve just updated my C circular buffer implementation, adopting the trick originally proposed by Philip Howard and adapted to Darwin by Kurt Revis: A virtual copy of the buffer is inserted directly after the end of the buffer, so that you can write past the end of the buffer, but have your writes automatically wrapped around to the start — no need to manually implement buffer wrapping logic.

This dramatically simplifies the use of a circular buffer — you can use chunks of the buffer without any need to worry about where the wrap point is.

See the new implementation, which is thread-safe with one consumer and one producer, with no need for locks, making it perfect for use with high-priority Core Audio threads, on GitHub: TPCircularBuffer.

There’s a basic example of its use over on the original post.

, , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

2 Comments

  1. Posted February 24, 2012 at 4:03 am | Permalink

    I was not able to fully understand the benefit for using virtual memory technique here. Are we able to do something faster ? Any related tutorial link ?

    • Posted February 24, 2012 at 9:34 am | Permalink

      Hi Vivek – the benefit is complete transparency for the wrap-around; you don’t have to worry where the boundary is.

      Here’s an article that Mike Ash wrote about mirrored memory buffers