Search code examples
c++optimizationvolatile

Partially volatile variable?


Suppose I have a micro controller with a main loop and 1 millisecond interrupt (if you don't know what that is it is just a task that interrupts the main loop's execution, while it does something.....and it is a 1 millisecond interrupt, because it happens every millisecond).

I have a variable that I use to communicate between the main loop and the millisecond interrupt:

volatile status_t Status;

Right now I have a section of code in the main loop that updates the Status variable, which does a ton of transformations on it:

cli();    // This temporarily turns off interrupts, so we don't 
          // modify the variable unsafely
Status.UpdateStuff();
Status.UpdateOtherStuff();
//etc.

sei();    // Turn interrupts back on

The problem is that each of these function calls to Status rewrites Status......the compiler can not cache the values of Status in local memory.

One possible solution to this problem is this:

cli();
status_t* localStatus = (status_t*)&Status;
localStatus->UpdateStuff();
localStatus->UpdateOtherStuff();
//etc.

Status = *localStatus;
sei();

The real question here is this:

Is this going to do what I hope it will do or is there a better way to get around the issue of constant refreshing the variable, instead of allowing the optimizer to cache the variable?


Solution

  • Your second version might still write to the microcontroller multiple times, because the compiler may not realize it can cache the value across method calls (it could probably only determine this if the methods are inline). So I suggest making an explicit local copy, not just a local pointer.

    cli();
    status_t localStatus = Status;
    localStatus.UpdateStuff();
    localStatus.UpdateOtherStuff();
    ...
    Status = localStatus;
    sei();