volatile in struct

Sergei Organov osv at topconrd.ru
Tue Feb 17 09:22:55 UTC 2004

Angelo Fraietta <afraiett at bigpond.net.au> writes:
> Sergei Organov wrote:
> >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.
> >
> 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) {

You may substitute semaphore with condition variable or any other
synchronization primitive you like.


More information about the users mailing list