473,396 Members | 1,968 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Writing Singleton Classes

Hi,

In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp.../10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.

The class is as follows:

class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};

The first implementation is:

Singleton* Singleton::pinstance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}

The second implementation makes a small change to the constructor:

Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}

The author notes that the second implementation is optimized for
single-threaded applications. Why would it not also work for
multi-threaded applications?

Thanks,
cpp

Jul 22 '05 #1
16 6672
cppaddict wrote:
Hi,

In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp.../10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.
...


I found an answer here :
http://blogs.msdn.com/oldnewthing/ar.../08/85901.aspx

Now, the first implementation is also problematic, and has
exactely the same problem: initialisation must be protected
by a mutex or something...

Benoit
Jul 22 '05 #2
cppaddict wrote:
Hi,

In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp.../10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.

The class is as follows:

class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
Looks to me like the *first* instance isn't thread safe, but the second is!
The first implementation is:

Singleton* Singleton::pinstance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{ What happens if a context switch occurs right here? After the if
statemnt, but before the new? pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}

The second implementation makes a small change to the constructor: Not a constructor, but the Singleton accessor. As far as I can tell, this *is* thread safe. Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}

The author notes that the second implementation is optimized for
single-threaded applications. Why would it not also work for
multi-threaded applications?


I think the author is full of it, but that's just *MY* opinion... I
could be wrong.

Jul 22 '05 #3
Now, the first implementation is also problematic, and has
exactely the same problem: initialisation must be protected
by a mutex or something...

Benoit


Thanks for the reference. That's very interesting....

What is a mutex though? After reading that article it seems that
Singletons are never thread safe.

Thanks,
cpp
Jul 22 '05 #4
cppaddict wrote:
Hi,

In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp.../10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.


cppaddict,

The first implementation needs a slight change to be thread-safe:

Singleton* Singleton::Instance ()
{
// In the common case, simply return the existing instance (no
locking required)
//
if (pinstance != 0)
return pinstance;

// If there was no instance above, we need to lock now and
double-check whether
// another thread created an instance in between the check above and
now
//
Lock();
if (pinstance == 0)
pinstance = new Singleton;
Unlock();

return pinstance;
}

There are a dozen or so Singleton articles on CodeProject; the following is
very good and covers threading issues:

Singleton Pattern: A review and analysis of existing C++ implementations
http://www.codeproject.com/cpp/singleton.asp
Tim
Jul 22 '05 #5
> What is a mutex though? After reading that article it seems that
Singletons are never thread safe.


Mutex means Mutual Exclusion (it's a mechanism that ensures
that at most one thread accesses a particular object at a
given time). See Tim Clacy's post: Lock() prevents other
threads from executing the sequence until Unlock() has been
called. Lock and Unlock can usually not be implemented with
high level standard instructions. It always involves some
machine specific instructions (disabling interruptions, ...)
but this is going to be very off-topic here and you will
have to switch to another group to get informations about
locking mechanisms.

Local static variables are not safe, but implementing a
Singleton with Tim Clacy's code is safe (provided that
Lock() and Unlock() are correct, of course) :

Lock();
if (pinstance == 0)
pinstance = new Singleton;
Unlock();

Benoit
Jul 22 '05 #6
Neither of the solutions in the article originally referenced are thread safe.

In a threaded program both could lead to undesired behavior such as double
construction or premature access.

One of the respondents to this thread posted an example of the Double Checked
Locking idiom.

Apparently even that is problematic as discussed by Scott Meyers in the
document @ http://www.nwcpp.org/Downloads/2004/DCLP_notes.pdf

Jul 22 '05 #7

"red floyd" <no*****@here.dude> wrote in message
news:hg****************@newssvr27.news.prodigy.com ...
As far as I can tell, this *is* thread safe.
Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}

No, its not. If the first thread is in the middle of construction, and get
preempted, the object is in an unknown state when the second thread attempts
access. This is safe from order dependencies during init., but not thread
safe. The opposite is true for the first form. It is thread-safe because
it is initialized before the application's main procedure runs and therefore
before the program can spawn any threads. It is not safe from order
dependencies if a staticly constructed object from a different file attempts
access to it during construction.

Jul 22 '05 #8

"Xenos" <do**********@spamhate.com> wrote in message
news:c8*********@cui1.lmms.lmco.com...

"red floyd" <no*****@here.dude> wrote in message
news:hg****************@newssvr27.news.prodigy.com ...
As far as I can tell, this *is* thread safe.
Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}
No, its not. If the first thread is in the middle of construction, and

get preempted, the object is in an unknown state when the second thread attempts access. This is safe from order dependencies during init., but not thread
safe. The opposite is true for the first form. It is thread-safe because
it is initialized before the application's main procedure runs and therefore before the program can spawn any threads. It is not safe from order
dependencies if a staticly constructed object from a different file attempts access to it during construction.


Looked at code to quick, the first is not thread-safe either. I thought it
was constructor at startup, not is not.

Jul 22 '05 #9

"Xenos" <do**********@spamhate.com> wrote in message
news:c8*********@cui1.lmms.lmco.com...
Looked at code to quick, the first is not thread-safe either. I thought it was constructor at startup, not is not.


Geesh! Now I'm just typing to fast.

....constructed at strartup, but it is not!
Jul 22 '05 #10

DaKoadMunky wrote:
[...]
One of the respondents to this thread posted an example of the Double Checked
Locking idiom.
The idiom has only one check for locking, not two. I guess that
someone had called it "the DCL" after 10th drink or so (they say
that after about 10th drink one tends not to count correctly
anymore). A much better name is "Double Checked Serialized
Initialization". There are two variations of DCSI. One with
atomic<>-with-msync::<stuff> and more portable one with thread-
specific data (e.g. "thread_specific_ptr<>") instead of
atomic<>-with-msync::<stuff> (and I don't mean thread-specific
singletons). There is also "Double Checked Concurrent
Initialization" idiom (lock-less and not for "singletons").

http://google.com/groups?selm=40867B...FEBFE%40web.de

Apparently even that is problematic as discussed by Scott Meyers in the
document @ http://www.nwcpp.org/Downloads/2004/DCLP_notes.pdf


Not bad up to Pg. 22. "Multiprocessors, Cache Coherency, and
Memory Barriers" part is somewhat screwed. For example, Pg. 34
and Pg. 35:

Keyboard* temp = pInstance;
Perform acquire;
...

(that notation sucks, BTW) is not really the same (with
respect to reordering) as

Keyboard* temp = pInstance;
Lock L1(args); // acquire
...

because the later can be transformed to

Lock L1(args); // acquire
Keyboard* temp = pInstance;
...

While it does stress the point of Pg. 36, the difference is
quite significant and it can really hurt you in some other
context. Beware.

regards,
alexander.

P.S. atomic<> is the way to go.
Jul 22 '05 #11


Alexander Terekhov wrote:

DaKoadMunky wrote:
[...]
One of the respondents to this thread posted an example of the Double Checked
Locking idiom.
The idiom has only one check for locking, not two. I guess that
someone had called it "the DCL" after 10th drink or so (they say
that after about 10th drink one tends not to count correctly
anymore). A much better name is "Double Checked Serialized
Initialization". There are two variations of DCSI. One with
atomic<>-with-msync::<stuff> and more portable one with thread-
specific data (e.g. "thread_specific_ptr<>") instead of
atomic<>-with-msync::<stuff> (and I don't mean thread-specific
singletons). There is also "Double Checked Concurrent
Initialization" idiom (lock-less and not for "singletons").

http://google.com/groups?selm=40867B...FEBFE%40web.de


Or you would just access the singleton via a reference in a handle
or object where correct visibility was established in the handle
or objects ctor, said objects being handled in the usual "threadsafe
as int" idiom.

....
P.S. atomic<> is the way to go.


except that there are several possibilities for atomic<> semantics
besides just the mutable/immutable stuff. There's atomic<T> vs.
atomic<*T>.

Joe Seigh
Jul 22 '05 #12

Joe Seigh wrote:
[...]
Or you would just access the singleton via a reference in a handle
or object where correct visibility was established in the handle
or objects ctor,


Yep. For example auto_unlock_ptr<>. That's what you need for mutable
"singletons" that don't use atomic<> internally. They need a lock
anyway and, usually, there's no problem to initialize the lock eagerly
or use something like lazy create-open-named-mutex trick on windows.
The situation is a bit different for immutable things (but you can
still use "expensive" get_instance() and cache the reference on the
callers side; in a way, that's what the TSD variation of DCSI does
internally).

regards,
alexander.
Jul 22 '05 #13


Alexander Terekhov wrote:

Joe Seigh wrote:
[...]
Or you would just access the singleton via a reference in a handle
or object where correct visibility was established in the handle
or objects ctor,


Yep. For example auto_unlock_ptr<>. That's what you need for mutable
"singletons" that don't use atomic<> internally. They need a lock
anyway and, usually, there's no problem to initialize the lock eagerly
or use something like lazy create-open-named-mutex trick on windows.
The situation is a bit different for immutable things (but you can
still use "expensive" get_instance() and cache the reference on the
callers side; in a way, that's what the TSD variation of DCSI does
internally).


I mean caching the reference in the object. In the object's ctor
you use DCL or one of your acronyms to create the singleton and
store the reference to the singleton in the object. The "safe
as int" visibility semantics guarantee proper visibility to the
singleton the same way they guarantee proper visibility of any
of the object's fields. It's not specific or local to the thread,
it's specific to the object using proper ownership rules.

If you are only accessing the singleton via the object's methods,
then it's pretty much transparent to the user. The only way
the user could get into trouble is by violating the "safe as int"
rule and they'd be in trouble even without a singleton involved.

Joe Seigh
Jul 22 '05 #14

DaKoadMunky wrote:

One of the respondents to this thread posted an example of the Double Checked
Locking idiom.

Apparently even that is problematic as discussed by Scott Meyers in the
document @ http://www.nwcpp.org/Downloads/2004/DCLP_notes.pdf


am i missing something here? why wouldn't this work:

Singleton* Singleton::Instance()
{
if (pinstance != 0)
return pinstance;

Lock();

if (pinstance == 0)
pinstance = makeSingleton();

Unlock();

return pinstance;
}

Singleton* Singleton::makeSingleton()
{
return new Singleton;
}

mark

Jul 22 '05 #15
Mark A. Gibbs wrote:

DaKoadMunky wrote:

One of the respondents to this thread posted an example of the Double
Checked
Locking idiom.

Apparently even that is problematic as discussed by Scott Meyers in the
document @ http://www.nwcpp.org/Downloads/2004/DCLP_notes.pdf

am i missing something here? why wouldn't this work:

Singleton* Singleton::Instance()
{
if (pinstance != 0)
return pinstance;

Lock();

if (pinstance == 0)
pinstance = makeSingleton();

Unlock();

return pinstance;
}

Singleton* Singleton::makeSingleton()
{
return new Singleton;
}

mark


Andrei Alexandrescu discusses this in "Modern C++ Design". It has to do
with memory architectures. In some cases, you need to do hardware
specific stuff to ensure cache coherency. He also recommends making
pinstance volatile.
Jul 22 '05 #16

red floyd wrote:
Andrei Alexandrescu discusses this in "Modern C++ Design". It has to do
with memory architectures. In some cases, you need to do hardware
specific stuff to ensure cache coherency. He also recommends making
pinstance volatile.


I had to dig up my copy to check what you meant, and the only concern I
could see addressed is based on architectures that queue up memory
writes. Is that what you meant?

In a case like this, couldn't you rewrite:

Singleton* Singleton::makeSingleton()
{
Singleton* temp = 0;

try
{
ImplementationSpecificLock();
Singleton* temp = new Singleton;
ImplementationSpecificUnlock();
}
catch(...)
{
ImplementationSpecificUnlock();
throw;
}

return temp;
}

for those implementations that require it?

On a side note, how common are such architectures?

Andrei Alexandrescu doesn't actually describe the type of singleton I
use most often, which is kind of a variation on the phoenix singleton.
I'm not sure if the pattern I use has a name, but it requires explicit
lifetime control, allows for optional construction (lazy instantiation)
and external locking and checking.

template <typename T>
class Singleton
{
public:
typedef implementation_defined Mutex;

static Mutex& GetMutex() { return mutex_; }

static bool InstanceExists() { return !(instance_ = 0); }

static T& Instance()
{
if (!InstanceExists()) throw SingletonDoesNotExistException;
return *instance_;
}

protected:
explicit Singleton(T* t = 0)
{
Mutex::Lock lock(GetMutex());

if (instance_) throw MultipleSingletonException;

instance_ = t ? t : static_cast<T*>(this);
}

~Singleton()
{
Mutex::Lock lock(GetMutex());

instance_ = 0;
}

private:
static Mutex mutex_;
static T* instance_;
};

And used like this:

class Foo : public Singleton<Foo>
{
public:
void func1();
void func2();
};

The thinking I've always used behind this design is that I'd like to be
responsible for when the mutex is locked and unlocked, although
individual functions are free to lock it just in case (multiple locks
within a thread are ok, but each lock must be matched by an unlock). I'd
also like to be able to control when and how the singleton is created,
and potentially replace it on the fly in some cases.

For example:

// In this case, I use Foo if it is available
Foo::Mutex::Lock lock(Foo::GetMutex());
if (Foo::InstanceExists()) { /*use it*/ }

// I can also call multiple functions without relocking
Foo::Mutex::Lock lock(Foo::GetMutex());
Foo& foo = Foo::Instance();
foo.func1();
foo.func2();

// And I can swap objects on the fly
class Base : public Singleton<Base>
{
public:
virtual ~Base();

virtual void func1() = 0;
virtual void func2() = 0;

protected:
Base();
};

class Derived1 : public Base
{
public:
void func1();
void func2();
};

class Derived2 : public Base
{
public:
void func1();
void func2();
};

Base::Mutex::Lock lock(Base::GetMutex());
Base* base = &Base::Instance(); // Currently a Derived1
delete base;
base = new Derived2;
Base& new_base = &Base::Instance();
new_base.func1();
new_base.func2();

This doesn't seem to suffer from any instruction ordering problem to me,
and the cached-memory-write architecture problem could be handled in the
mutex class. How does this measure up?

mark

Jul 22 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: weberjacob | last post by:
Sometimes I want to use certain data and functions anywhere in my code; for example, when writing logging routines. In PHP5 I could write a class with all static members and functions, a singleton...
2
by: Anurag K | last post by:
i have created a singleton class in a class file in my asp.net web application. this class is a singleton class. the code is: public class singletonclass { private static singletonclass sc =...
5
by: Jen | last post by:
I am fairly new to .NET and was wondering if someone could point me to a tutorial/overview of writing custom classes? Thank you.
2
by: Hadidi | last post by:
I want to make a class that : - will have one and only one object - when you try to make another object of this class , an IDE error should be seen . like using undefined variable , or any thing...
3
by: Ronen Yacov | last post by:
Hi everybody, When declaring a singleton, we write: static CMySingle::instance() { static CMySingle instance; return instance; }
4
by: ayan4u | last post by:
in a singleton class do we need to call a destructor explicitly....as everythng is made private there....
2
by: BLUE | last post by:
Since singleton classes conceptually are like static classes, the are supposed to last for the entire lifetime of the application. Starting from this point tell me if I'm wrong saying: - it make...
2
by: BLUE | last post by:
FirstClass members: - static int counter; - SingletonClass sc = SingletonClass.Instance; Moreovere FirstClass uses a static class named SecondClass with a static property...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.