From: bernard.fou...@kuantic.com

[...re: volatile use cases...]


> fourth case: nasty situations where 'volatile' is only a part of the 
> solution but does not insure a correct result:
> 
> For instance if ISR1 and ISR2 are *nested* ISRs, IsrCounter does not 
> correctly hold the count of interrupts:
> 
> volatile uint8_t IsrCounter;
> 
> ISR1()
> {
> IsrCounter++;
> }
> 
> ISR2()
> {
> IsrCounter++;
> }
> 
> Consider also memory locations larger than the MCU data processing unit 
> size (8 bits for AVR).
> 
> The following code gives bad results on an AVR but works on a i386:
> 
> volatile uint32_t MilliSeconds;
> 
> ISR()
> {
> MilliSeconds++;
> }
> 
> main()
> {
> while(MilliSeconds < SOME_LIMIT) ...
> }
> 


In both of these cases, "volatile" is insufficient because it does not imply 
"atomic".  In the first case, you need an atomic read-modify-write, and in the 
second you need an atomic read of a wide value.  In both cases you can achieve 
that by enclosing the the variable access in a cli-sei pair.  For example, the 
latter case can be fixed by changing the routine to something like

 

main()  // or "int main(void)", yada yada

{

   uint32_t ms;   // does not need to be volatile

 

   do{ cli(); ms = Milliseconds; sei(); } while (ms < SOME_LIMIT);

}

 

Regards,

 

   -=Dave

 

 

_________________________________________________________________
Stay up to date on your PC, the Web, and your mobile phone with Windows Live.
http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/
_______________________________________________
AVR-GCC-list mailing list
AVR-GCC-list@nongnu.org
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list

Reply via email to