in c++, to ensure singleton thread safe, how to do that? - c++

someone told me just to write singleton as a local class, is that true?
I am wondering why using the local class can ensure thread safety.

#include <boost/utility.hpp>
class singleton : private boost::noncopyable {
public:
static singleton& instance() {
static singleton inst;
return inst;
}
private:
singleton() = default;
~singleton() = default;
};
The construction of local static variables is guaranteed to be thread-safe.
Also, avoid singletons at all cost. They are just as terrible as globals are.

Take a look at this post: what is correspoding feature for synchronized in java?feature-for-synchronized-in-java
Basically it states that C++ doesn't has a language level feature for locking mechanisms, wich you need to make your singelton class threadsafe, though this articel http://en.wikipedia.org/wiki/Double-checked_locking about the Double Checked Locking Pattern states, that no locking is needed for singletons (an example is included for c).

Related

Is this a valid Singleton class

If I return a reference to my instance of MySingleton from GetInstance() instead of the pointer in my code below, it will be valid, but is using the pointer in this way also valid?
I assume my pointer will only get initialized once because it is static, but not not sure.
I know the correct way by using raw pointers within a singleton is to check if the pointer is first null before assigning it, but wondering if the below code is also valid. Thanks
class MySingleton
{
public:
static MySingleton* GetInstance()
{
static MySingleton* inst = new MySingleton();
return inst;
}
private:
MySingleton(){};
};
EDIT: I haven't seen this exact implementation for a Singleton implemented in the reported duplicate question
Your implementation is acceptable (as is any other) as long as any one of the following holds:
Your singleton does not acquire any external resources (anything: file handles, network connections, shared memory) for longer than a single exception-safe method invocation.
The last user of your singleton deletes the instance manually.
Otherwise something serious can leak.
You can wrap the instance in something automatic, like std::unique_ptr, but this immediately casts usual singleton lifetime issues.
See std::call_once and std::once_flag for implementing singleton pattern. Your implementation will lead to troubles in a multithreaded environment.
Most of is seem to have missed the simplest possible form of C++ singleton AKA Scott Meyer's Singleton. Ever since C++11 it has become as easy as a pie:
class singleton{
singleton();
singleton(singleton&&)=delete;
singleton(singleton const&)=delete;
void operator(singleton&&)=delete;
void operator(singleton const&)=delete;
//...
public:
static auto& singleton::instance(){
static singleton val{};
return val;
}
};
No need for complex code.

Lazy initialization with singleton pattern

Would the following code facilitate lazy initialization?
Or would the singletonInstance be created as soon as somebody includes the header (or even at program startup time)?
class SingletonClass
{
private:
SingletonClass();
~SingletonClass();
public:
static const SingletonClass& Instance()
{
static SingletonClass singletonInstance;
return singletonInstance;
}
};
This is known as the Meyers singleton and they are lazy instantiated.
There are some considerations:
the singletons will be destroyed at the end of the program in the reverse order in which they are created, so there can be dependency issues.
C++03 doesn't guarantee against race conditions in multithreaded environments.
The SingletonClass constructor will not be called earlier than somenone calls the Instance() method.
Thus yes, it facilitates lazy initialization.

Can everything in a singleton be static?

In C++, can all the members in a singleton be static, or as much as possible? My thought is, there is only one instance globally anyway.
While searching I did find a lot of discussions on static class in C#, but not familiar about that. Would like to learn about it too.
Whatever thought you have, please comment.
With a static singleton you can't control when the single will be allocated and constructed. This puts you at the mercy of the c++ order of construction rules for static variables, so if you happen to call this single during the construction of another static variable, the single may not exist yet.
If you have no intentions of ever calling the singleton from the constructor of another static variable, and do not wish to delay construction for any reason, using a static variable for singleton is fine.
See Static variables initialisation order for more info.
The singleton pattern, as you probably know, contains a static method Instance which will create the instance if and only if it exists and return that instance. There is no reason that other or all methods of the singleton could not be static. However, given that there is ever only one instance of the class i'm not sure it makes sense to make everything else static. Does that make sense?
Much of the point of a singleton is to have some control over when it's created.
With static data members you forfeit that control, for those members.
So it's less than smart doing that.
That said, singletons are generally Evilâ„¢ with many of the same problems as pure global variables, including the tendency to serve as an uncontrollable communications hub that propagates various unpredictable effects rather willy-nilly from unpredictable places to other unpredictable and largely unknown places, at unpredictable times.
So it's a good idea to think hard about it: is a singleton really the answer, or could it, in the case at hand, be just a way to compound the problem it was meant to solve?
To answer your question: The case you're suggesting is more like a 'static class' in C# and C++ doesn't have a concept of 'static class'.
Usually in a C++ singleton class, the only static data member is the singleton instance itself. This can either be a pointer to the singleton class or a simply an instance.
There are two ways to create a singleton class without the singleton instance being a pointer.
1)
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
static MySingletonClass instance;
return instance;
}
// non-static functions
private:
// non-static data-members
};
2)
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
return sInstance;
}
// non-static functions
private:
static MySingletonClass sInstance;
// non-static data-members
};
// In CPP file
MySingletonClass MySingletonClass::sInstance;
This implementation is not thread-safe, not predictable in terms of when it gets constructed or when it gets destroyed. If this instances depends on another singleton to destroy itself, it can cause unidentifiable errors when exiting your application.
The one with the pointer looks something like this:
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
return *sInstance;
}
static MySingletonClass* getInstancePointer()
{
return sInstance;
}
MySingletonClass()
{
if (sInstance) {
throw std::runtime_error("An instance of this class already exists");
}
sInstance = this;
}
// non-static functions
private:
static MySingletonClass* sInstance;
// non-static data-members
};
Inialization of such a singleton class would usually happen during application initialization:
void MyApp::init()
{
// Some stuff to be initalized before MySingletonClass gets initialized.
MySingletonClass* mySingleton = new MySingletonClass(); // Initalization is determined.
// Rest of initialization
}
void MyApp::update()
{
// Stuff to update before MySingletonClass
MySingletonClass::getInstance().update(); // <-- that's how you access non-static functions.
// Stuff to update after MySingletonClass has been updated.
}
void MyApp::destroy()
{
// Destroy stuff created after singleton creation
delete MySingletonClass::getInstancePointer();
// Destroy stuff created before singleton creation
}
Although the initalization and destruction of singleton is controlled in this scenario, singletons don't play well in a multi-threaded application. I hope this clears your doubts.
the short answer: yes! sure! C++ is flexible, and almost everything is possible (especially such a simple things).
the detailed answer depends on your use cases.
how may other statics/globals depends on your signleton
when the very first access to your singleton going to happen (probably before main?)
lot of other things you have to take in account (most of them related to interaction of your singleton w/ other entities)

C++ different singleton implementations

I usually implement the singleton pattern this way :
class Singleton
{
public:
virtual ~Singleton() {}
static Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
private:
Singleton();
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
}
Recently, I ran into this implementation, which is slightly different :
class Singleton
{
public:
Singleton();
virtual ~Singleton() {}
static Singleton& GetInstance()
{
return instance;
}
private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
static Singleton instance;
}
Singleton Singleton::instance;
Which implementation is better ?
Isn't it dangerous not to make the constructor private (2nd implementation) ?
Thanks.
There is a difference. In first case instance is initialized on first call of the function. In second case it is initialized when program starts.
If you make a public constructor - It's not a singleton, since it's can be created by anyone
I need not repeat the good point about lazy construction of the singleton made in other answers.
Let me add this:
public:
Singleton();
virtual ~Singleton() {}
The designer of this particular class felt a need to allow:
derivation from this Singleton class, say the derived class is called DerSingleton
DerSingleton can have instances which can be deleted with a pointer to Singleton (so DerSingleton is not a singleton)
Any instance of DerSingleton is also a Singleton instance by definition, so it follows that if DerSingleton is instanciated, Singleton is not a singleton.
So this design asserts two things:
this class is a singleton
this class is not a singleton
The main difference in behavior will come if you try to use the singleton during initialization of another namespace level variable or class static member. In the first case, because the actual object is created on demand during the first function call, the behavior during contruction will be well defined. In the second case, all bets are off, since the relative order of initialization of static objects from different translation units is undefined.
Also note that while the first one is safe during construction, it might not be during destruction. That is, if an object with static storage duration does not use the singleton during construction, it could be initialized before the singleton instance. The order of destruction is reversed from the order of construction, and in this particular case the singleton would be destroyed before the other object. If that object uses the singleton in its destructor, it will cause undefined behavior.
The second implementation is wrong. The default constructor should be private. As it is, it is not a singleton per se. Besides that, the differences between the implementations are mentioned in #Andrew and #Brady answers.
One important difference between the two is that the creation of the instance in the second example is thread-safe.
You're absolutely right though, the constructor should be private.
Here's a related question: https://stackoverflow.com/a/10479084/1158895

Can any one provide me a sample of Singleton in c++?

I write a singleton c++ in the follow way:
class A {
private:
static A* m_pA;
A();
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL)
m_pA = new A();
return m_pA;
}
A::~A() {
FreeInstance() // Can I write this? are there any potential error?
}
void A::FreeInstance() {
delete m_pA;
m_pA = NULL;
}
Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good!
My way is wrong, I wish any one writting such code can avoid my silly mistake.
My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.
//-----------------------------------------------------------
A new singleton, you are welcome to edit if you think there is any problem in the following sample:
class A {
private:
static A* m_pA;
explicit A();
void A(const A& a);
void A(A &a);
const A& operator=(const A& a);
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL){
static A self;
m_pA = &self;
}
return m_pA;
}
A::~A() {
}
Why does everybody want to return a singleton as a pointer?
Return it as a reference seems much more logical!
You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.
Use the static in a function method.
This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free.
class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {}
S(S const&); // Don't Implement.
void operator=(S const&); // Don't implement
};
Note you also need to make the constructor private.
Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).
Also read:
https://stackoverflow.com/a/1008289/14065
Singleton: How should it be used
C++ Singleton design pattern
To make sure you are using a singleton for the correct reasons.
Though technically not thread safe in the general case see:
What is the lifetime of a static variable in a C++ function?
GCC has an explicit patch to compensate for this:
http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html
You can avoid needing to delete it by using a static object like this:
if(m_pA == 0) {
static A static_instance;
m_pA = &static_instance;
}
A singleton in C++ can be written in this way:
static A* A::GetInstance() {
static A sin;
return &sin;
}
Just don't forget to make the copy constructor and assignment operators private.
I do not think there is any reason to write that line no. Your destructor method is not static and your singleton instance will not be destructed in that fashion. I do not think the destructor is necessary, if you need to cleanup the object use the static method you've alread created, FreeInstance().
Other than that, you create your singletons in roughly the same way that I create mine.
After a period of wild enthusiasm for Meyers-style singletons (using local static objects as in some of the previous answers), I got completely sick of the lifetime management problems in complicated apps.
I tend to find that you end up referencing the 'Instance' method deliberately early in the app's initialisation, to make sure they're created when you want, and then playing all kinds of games with the tear-down because of the unpredictable (or at least very complicated and somewhat hidden) order in which things get destroyed.
YMMV of course, and it depends a bit on the nature of the singleton itself, but a lot of the waffle about clever singletons (and the threading/locking issues which surround the cleverness) is overrated IMO.
if you read "Modern C++ Design" you'll realize that a singleton design could be much complex than return a static variable.
This implementation is fine as long as you can answer these questions:
do you know when the object will be created (if you use a static object instead of new? Do you have a main()?)
does you singleton have any dependencies that may not be ready by the time it is created? If you use a static object instead of new, what libraries have been initialized by this time? What your object does in constructor that might require them?
when will it be deleted?
Using new() is safer because you control where and when the object will be created and deleted. But then you need to delete it explicitly and probably nobody in the system knows when to do so. You may use atexit() for that, if it makes sense.
Using a static object in method means that do do not really know when it will be created or deleted. You could as well use a global static object in a namespace and avoid getInstance() at all - it doesn't add much.
If you do use threads, then you're in big trouble. It is virtually impossible to create usable thread safe singleton in C++ due to:
permanent lock in getInstance is very heavy - a full context switch at every getInstance()
double checked lock fails due to compiler optimizations and cache/weak memory model, is very tricky to implement, and impossible to test. I wouldn't attempt to do it in a real system, unless you intimately know your architecture and want it to be not portable
These can be Googled easily, but here's a good link on weak memory model: http://ridiculousfish.com/blog/archives/2007/02/17/barrier.
One solution would be to use locking but require that users cache the pointer they get from getInctance() and be prepared for getInstance() to be heavy.
Another solution would be to let users handle thread safety themselves.
Yet another solution would be to use a function with simple locking and substitute it with another function without locking and checking once the new() has been called. This works, but full implementation is complicated.
There is a great C++ library, ACE, based on patterns. There's a lot of documentation about different kind of patterns so look at their work:
http://www.cs.wustl.edu/~schmidt/ACE.html
//! #file singleton.h
//!
//! #brief Variadic template to make a singleton out of an ordinary type.
//!
//! This template makes a singleton out of a type without a default
//! constructor.
#ifndef SINGLETON_H
#define SINGLETON_H
#include <stdexcept>
template <typename C, typename ...Args>
class singleton
{
private:
singleton() = default;
static C* m_instance;
public:
singleton(const singleton&) = delete;
singleton& operator=(const singleton&) = delete;
singleton(singleton&&) = delete;
singleton& operator=(singleton&&) = delete;
~singleton()
{
delete m_instance;
m_instance = nullptr;
}
static C& create(Args...args)
{
if (m_instance != nullptr)
{
delete m_instance;
m_instance = nullptr;
}
m_instance = new C(args...);
return *m_instance;
}
static C& instance()
{
if (m_instance == nullptr)
throw std::logic_error(
"singleton<>::create(...) must precede singleton<>::instance()");
return *m_instance;
}
};
template <typename C, typename ...Args>
C* singleton<C, Args...>::m_instance = nullptr;
#endif // SINGLETON_H