Volatile is Necessary

Darin Johnson darin at laic.UUCP
Thu Mar 31 11:15:12 AEST 1988


In article <378 at ma.diab.UUCP>, pf at diab.UUCP (Per Fogelstr|m) writes:
> In article <7569 at brl-smoke.ARPA> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
> >You need a hell of a lot more than "volatile" to properly
> >synchronize concurrent processes.
> 
> I don't beleive that "volatile" was intended to be a mechanisim for
> processor synchronization, rather a way to indicate that a "memory"
> location has side effects, for example when it's read. For those of
> You that don't normally do system and driver programming it's qite
> meaningless, but boy how nice it is to be able to use the -O switch
> when compiling a driver wich requires fast interrupt turnaround.

For a real life example...  There are quite a few languages in VMS that
have a 'volatile' keyword as a language extension.  I have actually
needed to use something like this to do the following (synopsis):

  volatile int op_cnt;
  .
  .
  void read_ast(.....) {
    .
    .
    op_cnt += z; 
    .
    .
  }

  .
  .
  sys$qio(.., read_ast, ..); /* sys$qio will call read_ast() asynchronously */
  .
  .
  /* now do some expression involving op_cnt, pass it to a function, 
     take its address(!), etc. */

If the word volatile is removed, I could not get consistent results
when optimization was turned on.  This was because op_cnt can get
changed at anytime, even between an add and a store instruction.
If I explicitly turned off optimization (it is on by default) then
everything would start working fine.  Of course, the above code is
bad programming, but you should get the general idea.

A #pragma could be used instead, but if any sort of similar asynchronous
routines get put into a standard (POSIX or otherwise) then 'volatile' will
have to be used instead of '#pragma' to make the code portable (or
else require '#pragma volatile' to be in every compiler you want to
port to).
-- 
Darin Johnson (...ucbvax!sun!sunncal!leadsv!laic!darin)
              (...lll-lcc.arpa!leadsv!laic!darin)
	All aboard the DOOMED express!



More information about the Comp.lang.c mailing list