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

Miguel de Icaza miguel@ximian.com
28 Oct 2001 07:54:20 -0500


> However, runtime has some means to deal with delayed initialization.
> Note that we're talking only about _static_ properties here (perhaps,
> volatile prefix will help with instance fields?)

Mhm, this is indeed interesting.  

The reason I suggested the locking mechanism before was because I was
trying to avoid creating a lot of objects that might never be used (in
this particular case I was coding something in System.ComponentModel and
a bunch of static attributes are created, equivalent to a "public
constant" kind of thing).

In my case there was no point in creating all those things, as the user
program might never use them.   I am afraid we will find more of these
patterns in the code later.

Anders mentioned in his talk at the PDC that sprinkling "volatile" in a
variable would mean that the compiler/JITer would make sure that no code
is moved around this (acting as a barrier).  

So we could probably just make those static variables volatile, and make
sure that the JITer will on SMP systems perform a barrier on volatile
variable access.

> If beforefieldinit flag is omited from type signature, then cctor will be
> called only at the first access to type's static field or at invoking static
> method of the class. This is similar to Java semantics for static field
> initialization. And cctor is called only once.


> 
> However, I have no idea how to force C# compiler to generate such signatures
> or prefixes.

Oh!  I know how ;-)

If you have no static constructors, then static methods can be invoked
without initializing the type (we handle this correctly in MCS for
example ;-)

Miguel