[Mono-devel-list] Thread safety of readonly data members?

gabor gabor at z10n.net
Wed Feb 18 11:06:23 EST 2004

On Wed, 2004-02-18 at 12:49, Jonathan Pryor wrote:
> Moving on to Mono, one major problem is that the CLI standard, as
> currently specified, uses effectively the same memory consistency model
> as Java.  Meaning, C++ techniques such as double-checked locking ARE NOT
> 	private static Class1 foo;
> 	public static Foo {
> 		get {
> 			// This will likely work on most platforms, such
> 			// as x86, but it is NOT guaranteed to work on 
> 			// all potential hardware platforms.
> 			if (foo == null) {
> 				lock (typeof(Something)) {
> 					if (foo == null)
> 						foo = new Class1();
> 				}
> 			}
> 		}
> 	}
> In C++, you could use code similar to the above, and you WOULD NOT need
> to lock both the class constructor and the accessor methods, as the
> calling code ensures that the class has properly constructed before
> invoking any member functions.
> The problem is that double-checked locking isn't really portable in
> .NET, so you either need to (a) always lock the code that will construct
> the object, or (b) use the static loader lock, described below.

hmmm.. could you explain one more time why is that code wrong?
 for example can you give me an example when it goes wrong?

for me it seems that it really guarantees that only 1 thread will be
able to construct the object.

and btw.  is reading or writing a native/simple/non-object ( i don't
know the exact term for this. i mean something like int, char and so on)
an atomic operation?

for example if i have two threads, one writes to a variable randomly 1
or 10. the other thread reads the variable in a loop and writes it to
the screen. can i be sure that i will only see the numbers 1 and 10? 


More information about the Mono-devel-list mailing list