dinsdag 3 april 2018

Volatile C++ variables

// at the module level or somewhere else global to the function
int n;
while (n > 0)   { count++; }
will be readily transformed by an optimizing compiler as
if(n > 0)
    for(;;)
       count++;
and this is a perfectly valid translation. Because there is nothing in the loop that can change the value of n, there is no reason to ever test it again! This optimization is an example of a loop invariant computation, and an optimizing compiler will "pull this out" of the loop.

But what if the rest of the program looked like this:
registerMyThreadFlag(&n);
while(n > 0)
    {
     count++;
    }
and the thread used the variable registered by the registerMyThreadFlag call to set the value of the variable whose address was passed in? It would fail utterly; the loop would never exit!

Thus, the way this would have to be declared is by adding the volatile attribute to the declaration of n:
volatile int n;
This informs the compiler that it does not have the freedom to make the assumption about constancy of the value. The compiler will generate code to test the value n on every iteration through the loop, because you've explicitly told it that it is not safe to assume the value n is loop-invariant.

Geen opmerkingen:

Een reactie posten