[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: AW: [avr-gcc-list] Gcc bug??
From: |
Dave Hansen |
Subject: |
Re: AW: [avr-gcc-list] Gcc bug?? |
Date: |
Thu, 04 Mar 2004 09:33:53 -0500 |
<x-flowed>
From: Simon Han <address@hidden>
[...]
Am I correct on this? Could some compiler experts help to explain the
detail about volatile keyword in the context of embedded system? A
pointer to a page might work as well.
The "volatile" keyword is actually pretty simple. It tells the compiler
that
1) Something you can't see might change its value.
2) Writing the variable may cause side effects you don't know about.
Or even more simply, "Do exactly what I tell you to do with this variable in
exactly the order I tell you to do it. No more, no less."
Someone else pointed out the classical example of a loop controlled by a
flag. Given
while (flag == 0)
continue;
If "flag" is not volatile, he compiler is free to generate code functionally
identical to
if (flag == 0)
while (1)
continue;
Another example might be
flag = 1;
// code that does not read or write flag, or call any functions
flag = 0;
If flag is not volatile, the compiler could optimize out the first
assignment (of 1) to flag. If it matters that flag be 1 between the
assignments, make it volatile.
Something "volatile" will _not_ do is protect access. For example, if you
have a counter that is reset by an interrupt but incremented in mainline
code, e.g.
void check(void)
{
if (condition)
++ctr;
}
SIGNAL(SOMETHING_OR_OTHER)
{
ctr = 0;
}
This can fail _even_if_ ctr is volatile. To fix the code, the "check"
function must disable interrupts before incrementing ctr. Otherwise the
interrupt might occur in the middle of the increment operation, and the
value of ctr might be incorrect or corrupt.
HTH,
-=Dave
_________________________________________________________________
Frustrated with dial-up? Lightning-fast Internet access for as low as
$29.95/month. http://click.atdmt.com/AVE/go/onm00200360ave/direct/01/
_______________________________________________
avr-gcc-list mailing list
address@hidden
http://www.avr1.org/mailman/listinfo/avr-gcc-list
</x-flowed>
RE: AW: [avr-gcc-list] Gcc bug??, Dave Hansen, 2004/03/04
RE: AW: [avr-gcc-list] Gcc bug??, Dave Hylands, 2004/03/04