Author Topic: Is this Circular Event Buffer thread safe? (STM32G431)  (Read 69 times)

Dabbot and 3 Guests are viewing this topic.

Offline syntax333

  • Regular Contributor
  • *
  • Posts: 116
  • Country: 00
I created a circular buffer structure for my MCU(STM32G431) where elements of structure are:

  • EventBuffer[m]
  • Head
  • Tail

I use the events to drive a state machine. For my application ISRs are producers and my main is consumer. ISRs cannot preempt each other, each has same priority. ISRs push events to head index of event buffer and increment head variable while my main code pops events from tail index of event buffer and increment tail variable. If head or tail pointer reach end of the buffer they simply wrap around.

In main code I check the buffer like:
Code: [Select]
CircBuffer.Head = 0;
CircBuffer.Tail = 0;
enable_ISRs();

while(1){
  if(CircBuffer.Head == CircBuffer.Tail)
  {
  //Low power mode
  }
  else
  {
    statemachine_dispatch(CircBuffer.EventBuff[CircBuffer.Tail])
    increment CircBuffer.Tail & BUFFLEN_MASK
  }
}

In ISRs I add event to buffer like:

Code: [Select]
void example_ISR1()
{
  clear flag
  CircBuffer.EventBuff[CircBuffer.Head] = example_EVENT1;
  increment CircBuffer.Head & BUFFLEN_MASK
}
void example_ISR2()
{
  clear flag
  CircBuffer.EventBuff[CircBuffer.Head] = example_EVENT2;
  increment CircBuffer.Head & BUFFLEN_MASK
}

If I have to post an event to event buffer from main I disable and enable the interrupts.

I was wondering if this structure is thread safe or do I have to disable and enable the interrupts in my main loop while checking if buffer is empty (Head==Tail, No events to process) or dispatching the events or incrementing tail variable? Am I missing something?
 

Online capt bullshot

  • Super Contributor
  • ***
  • Posts: 2503
  • Country: de
    • Mostly useless stuff, but nice to have: wunderkis.de
Re: Is this Circular Event Buffer thread safe? (STM32G431)
« Reply #1 on: Today at 07:45:25 am »
I created a circular buffer structure for my MCU(STM32G431) where elements of structure are:

... snip ...

I was wondering if this structure is thread safe or do I have to disable and enable the interrupts in my main loop while checking if buffer is empty (Head==Tail, No events to process) or dispatching the events or incrementing tail variable? Am I missing something?

Looks fine to me. The interrupts don't use the tail pointer, and CPU read access to head pointers should be atomic, so the main will read always a valid variable. Don't forget to declare the pointers modified by the interrupts "volatile", otherwise the compiler might optimise your (Head == Tail) comparison out and you'll get never an input.
Safety devices hinder evolution
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf