avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: AW: [avr-gcc-list] Gcc bug??


From: Dave Hylands
Subject: RE: AW: [avr-gcc-list] Gcc bug??
Date: Wed, 3 Mar 2004 21:48:43 -0800

A better example of how NOT using volatile might cause a problem:

static uint8_t sync = 0;

void WaitForSync( void )
{
        while ( sync == 0 )
                ;
}

SIGNAL(SIG_OUTPUT_COMPARE0)
{
        sync = 1;
}

Since sync is NOT declared volatile, it can be optimized into a
register, and WaitForSync might never return.

Using volatile causes WaitForSync to refetch the value of sync from
memory each and every time it's accessed. That's essentially what
volatile does.

While we're talking about volatile, here's an example where volatile
might not help you (I've helped several people with this who had
misconceptions about what volatile does). Let's say I have a peripheral
which has a two register interface, the first register being an index
into an internal register and the second register gets the value.

struct hw
{
        uint8_t reg;
        uint8_t val;
};

struct hw *p;

void SetReg( uint8_t inReg, uint8_t inVal )
{
        p->reg = inReg;
        p->val = inVal;
}

It's possible for the compiler to reorder these to set val first and
then set reg. Declaring p as volatile will NOT change this behaviour.
The correct thing to do is use a technique like this:

void SetReg( uint8_t inReg, uint8_t inVal )
{
        p->reg = inReg;
        barrier();
        p->val = inVal;
}

void barrier( void )
{
}

The compiler won't change the order of statements across a function
call. For completeness, barrier should be in a different source file.

--
Dave Hylands
Vancouver, BC, Canada
http://www.DaveHylands.com/


_______________________________________________
avr-gcc-list mailing list
address@hidden
http://www.avr1.org/mailman/listinfo/avr-gcc-list


reply via email to

[Prev in Thread] Current Thread [Next in Thread]