On Wed, 1 Sep 2004, Mark Crispin wrote:
> there, so it's alright to keep testing it. On the other hand, this may
> not work if prefix increment is non-atomic; the C specification implies
> that it is, but it makes no definite statement.
There is no way for a C implementation to insure this is atomic unless the
hardware has an instruction to perform the operation atomically. If you
know your hardware has the facility, they you need to verify that your
compiler won't optimize the value into a register, etc.
When the hardware doesn't provide an atomic operation, the compiler would
have to generate mutex or other locking code around the variable, very
expensive considering that there is no way for a compiler to know if a
global value is modifed by other operations.
With modern desk top and larger computers, fetching or storing a 32 bit
value should be atomic. A trick I use to guard one-time code is:
if (!initialized) {
getmutex()
if (!initialized) { // real test guarded by mutex
do heavy lifting
initialized=TRUE
}
freemutex()
}
This approach is a light weight test for the common case that
initialization is complete but is 100% accurate since the test is repeated
under protection of the mutex.
Another trick, where an atomic data object is built, if building
multiple copies of the object won't waste too much memory (or for
languages such as Java with garbage collection):
if (!object) {
tempObject=makeTheObject()
object = tempObject
}
In this case, the object may be initialized multiple times until one of
the threads actually stores the result.
Dave Morris