Volatile are needed here?

I have a function where I update the structure and also disable interrupts.

bool readBuffer() { __disable_irq(); rb->reader += 1; // Just an example __enable_irq(); return true; } 

Since interrupts are disabled, it is not possible for another interrupt to be interrupted and im to update the values ​​in the structure.

But should the variabele reader also be marked as volatile ? Since, theoretically, another interrupt could preempt while I enter the function, but just before __disable_irq() actually called. And when my function resumes, the cached value of rb->reader will be wrong. Or does the compiler (GCC) generate code that does not rb->reader until this line is deleted?

+4
source share
1 answer

You might be better off indicating an explicit optimization barrier:

 bool readBuffer() { __disable_irq(); asm volatile ("" ::: "memory"); // Some unexpected memory modification rb->reader += 1; // Just an example __enable_irq(); return true; } 

This will be beneficial if in some other cases you want the compiler to optimize the rb->reader variable, and therefore its instability will be excessive.

+1
source

All Articles