Singleton in Action?

bauss jj_1337 at live.dk
Mon Feb 4 10:17:53 UTC 2019


On Saturday, 2 February 2019 at 16:56:45 UTC, Ron Tarrant wrote:
> Hi guys,
>
> I ran into another snag this morning while trying to implement 
> a singleton. I found all kinds of examples of singleton 
> definitions, but nothing about how to put them into practice.
>
> Can someone show me a code example for how one would actually 
> use a singleton pattern in D? When I did the same thing in PHP, 
> it took me forever to wrap my brain around it, so I'm hoping to 
> get there a little faster this time.
>
> Here's the singleton code I've been playing with:
>
> class DSingleton
> {
> 	private:
> 	// Cache instantiation flag in thread-local bool
> 	// Thread local
> 	static bool instantiated_;
>
> 	// Thread global
> 	__gshared DSingleton instance_;
>
> 	this()
> 	{
> 		
> 	} // this()
>
> 	public:
> 	
> 	static DSingleton get()
> 	{
> 		if(!instantiated_)
> 		{
> 			synchronized(DSingleton.classinfo)
> 			{
> 				if(!instance_)
> 				{
> 					instance_ = new DSingleton();
> 					writeln("creating");
> 				}
>
> 				instantiated_ = true;
> 			}
> 		}
> 		else
> 		{
> 			writeln("not created");
> 		}
>
> 		return(instance_);
> 		
> 	} // DSingleton()
>
> } // class DSingleton
>
> So, my big question is, do I instantiate like this:
>
> DSingleton singleton = new DSingleton;
>
> Or like this:
>
> DSingleton singleton = singleton.get();
>
> And subsequent calls would be...? The same? Using get() only?

Your code is not going to work in the way you think.

Ex. you state "instantiated_" is thread-local but that's the flag 
you use to check whether it has been instantiated.

That will not work.

Instead it should actually be shared, especially because you use 
it in a synchronized statement.

Also:

DSingleton singleton = new DSingleton;

Defeats the purpose of singleton.


More information about the Digitalmars-d-learn mailing list