From time to time,there is a need for dynamic buffer usage inside an application. One of the simple methods is just allocating and deallocating memory. This is however time consuming and leads to heap fragmentation, which continuously degrades performance. A good programmer always tries to reuse the allocated memory as much as possible. This leads to several techniques such as memory pools, which are preallocated memory buffers assigned dynamically to calling threads. In special cases where is a Buffer producer and Buffer consumer, another specific methods can be used. This can be a buffer queue as well as a circular buffer

 

I have always hated the later word,because it seemed extremely complicated. But the truth is that the idea is really simple. It however relies on linkage to other buffers. As illustrated in the image,each buffer knowns about its neighbours. To be honest,it just needs to know about the following buffer structure. It doesnt know how many buffers there are or how to contact a specific buffer,but it just knows one other buffer. Together with others,they are linked to a circle so that from B1 we can go to B2,then B3 and then back to B1 if we have only 3 buffers. Of course this “moving” direction is forward,but can be implemented backward if each buffer is linked with the previous buffer.

As we can see,the CircBuf class has 2 void pointers,which represents the previous and following buffers. Any other data type can be added of course. To create a specific amount of buffers,one has to create an array of these Buffer primitives. Once allocated,they need to be linked. I prefer to link the first and last buffer specifically and do the rest in a loop as its clear what’s happening.

Once buffers are allocated and linked, I do here for clarity a loop across the circular buffer. I choose an arbitrary buffer from the array (ID 0) and start looping, each time I advance to the following buffer and check its id, if the ID is 0, I decrease the id-crossing threshold and break if its zero,thus making sure that I have went through each of the buffers X-Times (6 times here). Hope somebody finds this useful :) 

 
 

Share This