volatile in struct

Eric Valette eric.valette at free.fr
Tue Feb 17 09:33:16 UTC 2004


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...

-- 
    __
   /  `                   	Eric Valette
  /--   __  o _.          	6 rue Paul Le Flem
(___, / (_(_(__         	35740 Pace

Tel: +33 (0)2 99 85 26 76	Fax: +33 (0)2 99 85 26 76
E-mail: eric.valette at free.fr






More information about the users mailing list