Threadsafe singleton using volatile,synchonized
BLS
nanali at foo.fr
Sat May 26 10:43:37 PDT 2007
Thanks Sean, indeed a very interesting thread.
>From 2004;It is really worth to browse the archives!
What is the reason/rationale for using volatile in this way ?
Another Question:
Is something like this available
CriticalSectionBegin()
{
// Your Single thread code goes here
}
CriticalSectionEnd()
Bjoern
Sean Kelly Wrote:
> BLS wrote:
> > Probabely I should use D-Learn instead but due to the fact that it is about compiler optimizing ... blah, blah ; Simple question : Is this singleton implementation thread safe ? Makes :
> > static volatile Singleton _instance
> > sense ?
> >
> > module pattern.singleton
> >
> > class Singleton
> > {
> > public:
> > static Singleton getInstance()
> > {
> > // double check lock
> > if (_instance is null)
> > {
> > synchronized {
> > if (_instance is null)
> > {
> > _instance = new Singleton();
> > }
> > }
> > }
> > return _instance;
> > }
> > private:
> > this() {}
> >
> > // do not optimize
> > static volatile Singleton _instance;
> > }
>
>
> No. The 'volatile' qualifier is applied to a statement, not a variable.
> You need to do something like this:
>
> # class Singleton
> # {
> # static Singleton s;
> #
> # Singleton instance()
> # {
> # volatile Singleton tmp = s;
> # if(!tmp)
> # {
> # synchronized
> # {
> # tmp = s;
> # if(!tmp)
> # {
> # volatile tmp = new Singleton();
> # s = tmp;
> # }
> # }
> # }
> # return s;
> # }
> # }
>
> This is from:
>
> http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=9260
>
> in thread:
>
> http://www.digitalmars.com/d/archives/digitalmars/D/9149.html#N9231
>
>
> Sean
More information about the Digitalmars-d
mailing list