Tuesday, February 16, 2021

Python Circular Buffer

Just to continue the series about watching me learning Python, here is one that might be useful for any  application that samples data in real time into a circular buffer, aka ring buffer. This examples runs two threads, one thread is "reading" (creating) data and depositing this data into the ring buffer, while the other thread reads a certain amount of said data independently.
Obviously, the ring buffer is in shared memory (global) and accessible by both threads.
Of course, putting random numbers into a buffer in a particular frequency and reading said buffer out with a different frequency is not solving any real problems, however, this is supposed to demonstrate how two threads could be used for sampling and analyzing data.

from time import sleep
from threading import Thread
import random

def read_val(var):
    length=len(var)
    global pos
    while True:
        for i in range(length):
            var[i]=random.random()
            pos=i
            print("generated ",i, var[i])
            sleep(0.5)

def pick_val(var):
    length=len(var)
    while True:
        sleep(0.1)
        print("most recent ",pos,var[pos])
        for i in range(length):
            lpos=(pos+i)%length
            print("=> ",i,var[i],lpos,var[lpos])

# initialize memory
data = []
for i in range(5):
    data.append(0)

t1 = Thread(target=read_val, args=(data,))
t2 = Thread(target=pick_val, args=(data,))

t1.start()
t2.start()