volatile in struct

Sergei Organov osv at topconrd.ru
Tue Feb 17 09:41:15 UTC 2004


Eric Valette <eric.valette at free.fr> writes:
> Sergei Organov wrote:
> > Angelo Fraietta <afraiett at bigpond.net.au> writes:
> 
> >>>2. Using volatile is almost never a good idea. If you use RTOS primitives
> >>>  for mutual exclusion correctly, you don't need volatile for your
> >>>  protected data.
> 
> That's true for code modified in different context (e.g especially ISR)
> >>>
> >>
> >>I would have to dissagree with that. If I had a loop eg
> >>
> >>while (x)
> >>    {
> >>       do something
> >>    }
> >>
> >>And x is decremented in another thread, the compiler can optimise x so it
> >>will never appear changed without volatile
> > Actually your code exactly shows why volatile is evil most of times. The
> > code
> 
> > above should be avoided in applications as it is busy-waiting eating
> > processor time, -- and that was my point, -- as soon as you think you need
> > 'volatile' in your code, think more, -- most probably you are going to
> > make a mistake. (Sometimes there *is* need for 'volatile', e.g., access to
> > hardware registers, that's why I've put "almost" in my initial reply). The
> > above code in an RTOS-friendly application could look like this:
> 
> > while(1) {
> 
> >   semaphore_obtain(semaphore);
> >   do_something;
> > }
> > You may substitute semaphore with condition variable or any other
> 
> > synchronization primitive you like.
> >
> 
> 
> Except It doe not work in ISR context. With PCI mapped devices or any memory
> mapped controller registers, you usually have a loop in the ISR code like :
> 
> While (Device->IRQ_Status != NO-IRQ_PENDING)
> 	processIrQ ();
> 
> and YES IRQ status has to be volatile and no you cannot synchrnyse with
> anything else...

Did I say volatile is *never* useful?! Citing myself:

  "Using volatile is almost never a good idea."

Do you see "almost"? Another citation:

 "Sometimes there *is* need for 'volatile', e.g., access to hardware
 registers"

... and your example is nothing else but hardware register access.

What's your point here?

-- 
Sergei.




More information about the users mailing list