Singleton question (shared class)

Steven Schveighoffer schveiguy at yahoo.com
Wed Jan 25 07:35:13 PST 2012


On Wed, 25 Jan 2012 09:50:57 -0500, Mars <- at -.-> wrote:

> Alternative approach, I just found:
> http://pastie.org/private/1jlcvfostnbopfp3quflg
> If I get that right, this is basically the classic singleton, like it  
> would be in other languages, right?
> So... what's the best way?

This is an ok approach, but you must handle all threading issues  
manually.  In fact, you need to even with the shared version.  I don't  
know how threading support works with MySQL, so it may be ok just to  
ignore threading issues.  I'm not sure.

Another approach is to use thread local storage to have a singleton per  
instance.  This avoids the whole problem of sharing the instance.

An issue with your singleton allocation, is that you don't do the check  
for the instance being null while synchronized.  The singleton pattern  
looks like this:

static T instance;

T get()
{
    if(instance is null)
    {
       synchronized if(instance is null)
       {
           instance = new T;
       }
    }
    return instance;
}

The second check is necessary to avoid allocating multiple instances (they  
will get thrown away, but no need to create them).

Normally, you'd mark instance as volatile, but D2 doesn't support volatile  
any more.  I don't know the correct way to make sure the second check  
isn't optimized out.

-Steve


More information about the Digitalmars-d-learn mailing list