[Mono-list] Class library developers: locking issues to keep in mind

Miguel de Icaza miguel@ximian.com
27 Oct 2001 17:02:35 -0400


   I noticed today that I have been writing thread-unsafe code in my
code that goes into the class libraries.  Some classes for example
provide static properties, and to avoid a costly initialization at
bootstrap time, you want to create some of those values on demand
instead of doing it constructor, like this:

   class Sample {
	static SomeObject MyProperty {
		get {
			if (some_object == null)
				some_object = new SomeObject ();
			return some_object;
		}
	}
   }

   Well, it turns out that the code above is not thread safe, because
two threads might be hitting the same spot at the same time and two
copies of SomeObject would be created.  Then later on, comparissions
would not work (if p == MyProperty).  To correct that situation, you
have to lock on either the instance (this) or the class (typeof (this)),
like this:

    class Sample {
	static SomeObject MyProperty {
		get {
			if (some_object != null)
				return some_object;
			lock (typeof (Sample)){
				if (some_object == null)
					some_object = new SomeObject ();
				return some_object;
			}
		}
	}
    }

   Notice that you first test for initialization: if it is not null, you
can return the value without ever locking.  You only lock (which is an
expensive operation) if the value needs to be computed.

   Now, notice how we test for the value *inside* the lock.  This is
important because the value might have been initialized in a separate
thread before we reach lock.

Miguel.