[fpc-pascal] How to implement a circular buffer object in pascal?

Bo Berglund bo.berglund at gmail.com
Tue Sep 8 17:03:41 CEST 2020


On Mon, 7 Sep 2020 14:45:31 -0700 (MST), Brian via fpc-pascal
<fpc-pascal at lists.freepascal.org> wrote:

>Bo,
>
>Most of the users on this forum have never interfaced with hardware , as you
>can see from the responses. Those who have interfaced with hardware have
>developed circular buffers which they  know work , and they reuse them again
>and again.

I did this about 10 years ago when working on a PIC project with
serial data coming in from sensors and such, using Ansi-C.
And the buffer was just an array of char (byte in pascal) and there
was a read and a write index. The read index was only ever changed by
the consumer and the write index by the interrupt routine when adding
data.

The data reception was done in the interrupt and the code stuffed the
data into the array using ++ syntax for the index, with a check for
overflowing the array and then setting the index back to zero.

There was probably also an overrun detection and action if the
consumer is not fast enough, but I do not remember now...

>
>The following assumes you are receiving data from a sender , and in this
>case the sender and receiver are connected via 1Gbps Ethernet using Synapse
>(works really well).
>
>
>A thread receives data into an array of byte. RxBuffer : Array[0..1500] of
>byte  ... and copies the number of bytes received into a circular buffer ,
>which is an array of RxBuffer.

This is where I lose you, are you saying the circular buffer is not
individual bytes but something larger? What is the size of RxBuffer?
Looks like it is an array of byte, can you then make an array of such
arrays?

>
>In pseudo code it looks like this ...
>CircularBuffer : Array[0..N] of RxBuffer
>There is a ReadIndex and a WriteIndex , both longword or longint.
>
>The thread moves the data into the circular buffer continuously  increase
>the WriteIndex each write of RxBuffer data. If the WriteIndex > N then
>WriteIndex := 0 , otherwise it is increased by 1.
>
>The main loop (below)  moves the byte data using MOVE from CircBuffer to
>whatever structure it represents , increase the ReadIndex by one and decodes
>the data as needed.

Looks like an array of some bigger datatype then. But if so then one
needs to be able to detect in the receiver that enough data has
arrived to make one such object to put onto the next buffer...

>
> If ReadIndex <> WriteIndex then
>  .. do the work as described above and increment the ReadIndex
>
>I use the Free Pascal unit which allows suspending the thread while the
>ReadIndex is being increased. In the old DOS/DPMI days we would disable
>interrupts briefly.

Do you use CriticalSection for this?

>If you are innterested I can send you code snippets showing exactly how to
>implement the circular buffer.
>

Please do, thanks!

-- 
Bo Berglund
Developer in Sweden



More information about the fpc-pascal mailing list