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

Brian vmst at golden.net
Mon Sep 7 23:45:31 CEST 2020


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 will describe in general terms the structure a circular buffer implemented
to receive data , as it is usually more difficult to received the data than
to send it due to the asynchronism between the sender and receiver.
It has been used for many years , starting in 16bit-DOS , the 32bit-DPMI
using interrupt handlers , then Linux using threads. The concept is the same
for versions.

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.

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.

 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.

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

Regards
Brian
 







--
Sent from: http://free-pascal-general.1045716.n5.nabble.com/


More information about the fpc-pascal mailing list