volatile (in comp.lang.c)

Rob Warnock rpw3 at amdcad.AMD.COM
Fri May 27 13:54:46 AEST 1988


+---------------
| >    int x = v	/* A1 */	|	v = 2	/* B1 */
| >    int y = v	/* A2 */	|	
| > If the C compiler generates a memory fetch for each access to v, A's 
| > variables x and y will contain 1 and 2 respectively...
| > ...variable v must be declared volatile.
| Unfortunately, this is not sufficient.  "Volatile" does not guarantee
| that operations are atomic.  It is entirely possible for x and/or y to
| contain trash because they caught the variable midway through the
| assignment.  (Not likely to be a problem with the values 1 and 2, but
| 123534234 and 878787970 are a different matter.)
+---------------

Note that 12345678 is likely to be a problem only on machines for which the
memory bus is not wide enough to represent 12345678 in a single "write" cycle.

There is a perfectly respectable mutual exclusion technique which can be
used on multi-processor machines, which requires no special hardware, and
requires only that writes of a small integer are atomic. (The "small integer"
has to be able to hold a processor number.) In the two-processor case, this
is called "Dekker's Algorithm".  (For large numbers of processors, it is
called "expensive"!  ;-}  ;-}  )

The "volatile" type is necessary and sufficient for correctly implementing
Dekker's Algorithm in "optimizing C".


Rob Warnock
Systems Architecture Consultant

UUCP:	  {amdcad,fortune,sun,attmail}!redwood!rpw3
ATTmail:  !rpw3
DDD:	  (415)572-2607
USPS:	  627 26th Ave, San Mateo, CA  94403



More information about the Comp.lang.c mailing list