why do you need volatile?

Rick Genter x18 reg%lti.UUCP at bu-it.bu.edu
Fri Jun 3 07:26:55 AEST 1988


If anyone still (!) doesn't understand why volatile is necessary,
look at the March, 1988 issue of the Microsoft Systems Journal,
page 23, which contains a listing of a sample program that uses
multiple threads of execution within a single process.  There is
a boolean variable called bContinueCalc which gets set to FALSE 
when the calculation loop is supposed to abort.  The calculation
loop is

	for (A = 1.0, i = 0 ; i < iCalcRep ; i++) {
		if (! bContinueCalc)
			break;

		A = Savage (A);
	}

The other thread of execution deals with the user interface (the
Presentation Manager in OS/2).  If the ABORT button is clicked on,
the variable bContinueCalc is set to FALSE.  bContinueCalc is a
global variable declared as

	BOOL bContinueCalc = FALSE;

It should be declared

	volatile BOOL bContinueCalc = FALSE;

otherwise the C compiler is perfectly justified taking the test of
bContinueCalc out of the for loop, thus invalidating the whole use
of the variable.

					- reg

(P.S. Don't flame me about the naming conventions, OS/2, etc.  I'm
just citing an example; I don't claim to *like* any of what I cited.)
--
Rick Genter					...!buita!lti!reg
Language Technology, Inc.			reg%lti.uucp at bu-it.bu.edu
27 Congress St., Salem, MA 01970		(617) 741-1507



More information about the Comp.lang.c mailing list