Xref: utzoo comp.lang.c:10412 comp.arch:4986 Path: utzoo!utgpu!water!watmath!clyde!att!ihnp4!amdcad!rpw3 From: rpw3@amdcad.AMD.COM (Rob Warnock) Newsgroups: comp.lang.c,comp.arch Subject: Re: volatile (in comp.lang.c) Message-ID: <21821@amdcad.AMD.COM> Date: 27 May 88 03:54:46 GMT References: <20345@pyramid.pyramid.com> <833@mcdsun.UUCP> <1988May23.003847.1114@utzoo.uucp> Reply-To: rpw3@amdcad.UUCP (Rob Warnock) Organization: [Consultant] San Mateo, CA Lines: 34 +--------------- | > 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