Chris Newby wrote:
Thanks Ignacio ... actually I made a mistake in the declaration. The private
field "resource" should have been declared volatile:
private static volatile object resource;
this would ensure that if one thread begins writing to "resource" any other
thread is blocked from reading it until the write operation is complete ...
correct?
No. Reads and writes to aligned, native-word-sized fields and smaller,
are atomic, but that isn't affected by volatile and the situation is
much more complicated.
Volatile affects a mental model of how reads and writes of fields work
(aka the memory model). Basically, reads can't move before of a read of
a volatile field, and nor can writes move after the write of a volatile
field. The semantics are quite mind-bending.
And these reads and writes have nothing to do with CPU caches, in case
you read that elsewhere - CPU caches have cache coherency logic which
takes care of that itself, at performance cost. Rather it can affect the
order of retiring of memory commands within the processor (very
low-level stuff) or the level of aggressiveness of compiler
optimizations permitted.
Check here for the hairy details:
http://discuss.develop.com/archives/...=DOTNET&P=R375
and more from the same author here:
http://msdn.microsoft.com/msdnmag/is...s/default.aspx
And here (the second example) is a correct implementation of the pattern
you're after:
http://blogs.msdn.com/brada/archive/...12/130935.aspx
There is a slight contradiction between these two sources for the
correctness of the first example on Brad's page. Viewing 'volatile' as
stopping writes moving after the write of a volatile field, it would
appear that having the singleton field volatile will prevent "delayed
publication" of the Singleton's private fields, if any, as initialized
in the constructor. However, Vance suggests otherwise in the first
article, but if I read the second one correctly, the fact that the field
is volatile (he refers to a "head field" in a linked list in the second
article) should prevent late publication of private fields set in the
constructor.
Technically, volatile isn't required on x86, nor the .NET 2.0 memory
model, because writes can't change order (on the same thread).
-- Barry
--
http://barrkel.blogspot.com/