Re: psql use of 'volatile'

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: Bruce Momjian <pgman@candle.pha.pa.us>
Cc: PostgreSQL-development <pgsql-hackers@postgreSQL.org>
Date: 2000-06-30T01:19:58Z
Lists: pgsql-hackers
Bruce Momjian <pgman@candle.pha.pa.us> writes:
> Can someone explain why 'volatile' is used in psql/mainloop.c?  Seems
> volatile is only for hardware-specific variables that can not be
> optimized.

Not at all.  The ANSI C spec specifically says that you must declare
as volatile any local variables that you need to change after a
setjmp() call.  This prevents the compiler from putting them in
registers, which would cause their post-longjmp values to be
uncertain.  The exact statement is that after a longjmp,

       [#3] All accessible objects  have  values  as  of  the  time
       longjmp  was  called,  except  that the values of objects of
       automatic storage duration that are local  to  the  function
       containing  the invocation of the corresponding setjmp macro
       that do not  have  volatile-qualified  type  and  have  been
       changed  between  the setjmp invocation and longjmp call are
       indeterminate.

The reason they're "indeterminate" is that longjmp restores all the
machine registers to the values saved by setjmp.  So, if your local
variable foo was allocated in a register, then foo reverts to its
value as of the time of setjmp; but if it's in memory, it doesn't
revert.  The behavior is really perfectly "determinate", but you
can't safely rely on which will happen.  Unless you force foo to be
allocated in memory, which you do by labeling it "volatile".

This is sort of an abuse of the intuitive meaning of "volatile",
but it falls right out of what the qualifier actually means to a C
compiler, which is "keep this in memory, not in a register, and
fetch it afresh from memory every single time the program references
it.  No common-subexpression elimination here!"

			regards, tom lane