volatile (in comp.lang.c)

Henry Spencer henry at utzoo.uucp
Mon May 23 10:38:47 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.  If the compiler
> does not generate a memory fetch for each access, x and y will both
> contain 1.  To get behaviour that is the same for all compilers, the 
> 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.)  "Volatile" makes *no*
promises about how things will look in parallel processes; C is defined
as a sequential language.  (Please don't bring up signal handlers as an
exception unless you have read the very careful weasel-wording about them
in recent X3J11 drafts.)

With very careful cooperation from compiler and hardware, "volatile" may
permit such things to be done safely.  But that is an implementation-
dependent property, not a requirement of the language that all compilers
must satisfy.
-- 
NASA is to spaceflight as            |  Henry Spencer @ U of Toronto Zoology
the Post Office is to mail.          | {ihnp4,decvax,uunet!mnetor}!utzoo!henry



More information about the Comp.lang.c mailing list