Electronic – Concurrency issues with circular buffer in embedded program

embedded

I am working on an embedded program on the TM4C123GH6PM microcontroller from the Texas Instruments Tiva C Series LaunchPad.

The program is supposed to sample an external ADC in a timer interrupt and push the converted values into a queue (in this case a array-based circular buffer).

The main loop is transferring the values (popping bytes out of the queue) to a PC through the UART.

Inside the timer interrupt, a check is done to ensure that space is available in the queue. If so, bytes are pushed onto the queue.
If not, it stops the timer. The main loop will transfer the remaining bytes and start the timer again once the queue is empty (all bytes have been transferred).

My problem is that the timer is not always stopped even if the queue is full.

Could this be a concurrency problem? If so, how do I solve it?

By the way, I have played around with locks but this causes deadlocks. I have also ensured that the queue and related variables accessed both by the main loop and the timer interrupt is declared volatile.

Thanks in advance 🙂

Best Answer

If your queue has exactly one producer and one consumer make sure consumer has higher priority at all times. After this is achieved the concurrency won't cause any issues. Implementation depends on the hardware used, here's (my) code using such a queue on PIC24 micro -> https://github.com/felis/lcdtune/blob/master/lcdtune.c . The queue, as well as head and tail are defined here -> https://github.com/felis/lcdtune/blob/master/lcdtune.c#L50 , the producer is here -> https://github.com/felis/lcdtune/blob/master/lcdtune.c#L233 , and the consumer (the ISR) is here -> https://github.com/felis/lcdtune/blob/master/lcdtune.c#L102