Now that C++11 has multithreading I was wondering what is the correct way to implement lazy initialized singleton without using mutexes(for perf reasons).
I came up with this, but tbh Im not really good at writing lockfree code, so Im looking for some better solutions.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
# include <atomic>
# include <thread>
# include <string>
# include <iostream>
using namespace std;
class Singleton
{
public:
Singleton()
{
}
static bool isInitialized()
{
return (flag==2);
}
static bool initizalize(const string& name_)
{
if (flag==2)
return false;// already initialized
if (flag==1)
return false;//somebody else is initializing
if (flag==0)
{
int exp=0;
int desr=1;
//bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr)
bool willInitialize=std::atomic_compare_exchange_strong(&flag, &exp, desr);
if (! willInitialize)
{
//some other thread CASed before us
std::cout<<"somebody else CASed at aprox same time"<< endl;
return false;
}
else
{
initialize_impl(name_);
assert(flag==1);
flag=2;
return true;
}
}
}
static void clear()
{
name.clear();
flag=0;
}
private:
static void initialize_impl(const string& name_)
{
name=name_;
}
static atomic<int> flag;
static string name;
};
atomic<int> Singleton::flag=0;
string Singleton::name;
void myThreadFunction()
{
Singleton s;
bool initializedByMe =s.initizalize("1701");
if (initializedByMe)
s.clear();
}
int main()
{
while (true)
{
std::thread t1(myThreadFunction);
std::thread t2(myThreadFunction);
t1.join();
t2.join();
}
return 0;
}
Note that clear() is just for testing, real singleton wouldnt have that function.
C++11 removes the need for manual locking. Concurrent execution shall wait if a static local variable is already being initialized.
ยง6.7 [stmt.dcl] p4
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
As such, simple have a static function like this:
static Singleton& get() {
static Singleton instance;
return instance;
}
This will work all-right in C++11 (as long as the compiler properly implements that part of the standard, of course).
Of course, the real correct answer is to not use a singleton, period.
Maybe the easiest way to implement a singleton using C++11 is:
WARNING: Although this works according to the C++11 standard (static initialisers are thread-safe), this is not implemented correctly in Microsoft Visual C++ 2012 (static initialisers are NOT thread-safe). If you are targeting VC2012, then you have to use a different approach, as it does not fully implement the C++11 standard.
class Singleton {
public:
static Singleton& Instance() {
// Since it's a static variable, if the class has already been created,
// it won't be created again.
// And it **is** thread-safe in C++11.
static Singleton myInstance;
// Return a reference to our instance.
return myInstance;
}
// delete copy and move constructors and assign operators
Singleton(Singleton const&) = delete; // Copy construct
Singleton(Singleton&&) = delete; // Move construct
Singleton& operator=(Singleton const&) = delete; // Copy assign
Singleton& operator=(Singleton &&) = delete; // Move assign
// Any other public methods.
protected:
Singleton() {
// Constructor code goes here.
}
~Singleton() {
// Destructor code goes here.
}
// And any other protected methods.
}
IMHO, the best way to implement singletons is with a "double-check, single-lock" pattern, which you can implement portably in C++ 11:
Double-Checked Locking Is Fixed In C++11
This pattern is fast in the already-created case, requiring only a single pointer comparison, and safe in the first-use case.
As mentioned in previous answer, C++ 11 guarantees construction-order safety for static local variables Is local static variable initialization thread-safe in C++11? so you are safe using that pattern. However, Visual Studio 2013 does not yet support it :-( See the "magic statics" row on this page, so if you are using VS2013 you still need to do it yourself.
Unfortunately, nothing is ever simple. The sample code referenced for the pattern above cannot be called from CRT initialization, because the static std::mutex has a constructor, and is thus not guaranteed to be initialized before the first call to get the singleton, if said call is a side-effect of CRT initialization. To get around that, you have to use, not a mutex, but a pointer-to-mutex, which is guaranteed to be zero-initialized before CRT initialization starts. Then you would have to use std::atomic::compare_exchange_strong to create and use the mutex.
I am assuming that the C++ 11 thread-safe local-static-initialization semantics work even when called during CRT initialization.
So if you have the C++ 11 thread-safe local-static-initialization semantics available, use them. If not, you have some work to do, even moreso if you want your singleton to be thread-safe during CRT initialization.
template<class T>
class Resource
{
Resource<T>(const Resource<T>&) = delete;
Resource<T>& operator=(const Resource<T>&) = delete;
static unique_ptr<Resource<T>> m_ins;
static once_flag m_once;
Resource<T>() = default;
public :
virtual ~Resource<T>() = default;
static Resource<T>& getInstance() {
std::call_once(m_once, []() {
m_ins.reset(new Resource<T>);
});
return *m_ins.get();
}
};
It is hard to read your approach as you are not using the code as intended... that is, the common pattern for a singleton is calling instance() to get the single instance, then use it (also, if you really want a singleton, no constructor should be public).
At any rate, I don't think that your approach is safe, consider that two threads try to acquire the singleton, the first one that gets to update the flag will be the only one initializing, but the initialize function will exit early on the second one, and that thread might proceed to use the singleton before the first thread got around to complete initialization.
The semantics of your initialize are broken. If you try to describe / document the behavior of the function you will have some fun, and will end up describing the implementation rather than a simple operation. Documenting is usually a simple way to double check a design/algorithm: if you end up describing how rather than what, then you should get back to design. In particular, there is no guarantee that after initialize completes the object has actually been initialized (only if the returned value is true, and sometimes if it is false, but not always).
#pragma once
#include <memory>
#include <mutex>
namespace utils
{
template<typename T>
class Singleton
{
private:
Singleton<T>(const Singleton<T>&) = delete;
Singleton<T>& operator = (const Singleton<T>&) = delete;
Singleton<T>() = default;
static std::unique_ptr<T> m_instance;
static std::once_flag m_once;
public:
virtual ~Singleton<T>() = default;
static T* getInstance()
{
std::call_once(m_once, []() {
m_instance.reset(new T);
});
return m_instance.get();
}
template<typename... Args>
static T* getInstance2nd(Args&& ...args)
{
std::call_once(m_once, [&]() {
m_instance.reset(new T(std::forward<Args>(args)...));
});
return m_instance.get();
}
};
template<typename T> std::unique_ptr<T> Singleton<T>::m_instance;
template<typename T> std::once_flag Singleton<T>::m_once;
}
This version complies to be concurrent free where c++11 standard is not guaranteed to be 100% supported. It offers also a flexible way to instantiate the "owned" instance.
Even if the magic static word is enough in c++11 and greater the developer may have the necessity to get much more control over the instance creation.
Related
What is a once_flagsupposed to be initialized to? I've tried false and 0, and both have given errors similar to below (below is 0):
no viable conversion from 'int' to 'std::once_flag'
Here's how I am trying to use it. (I consider it bad style to not initialize statics even though the language initializes them, so I'd really prefer to have something there).
MyClass& GetMyClass()
{
static std::once_flag flag;
static MyClass cls;
std::call_once(flag, []() {
// Initialize class
});
return cls;
}
Update
If we look at the draft C++ standard section 30.4.4.1 Struct once_flag we can see the constructor is defined as:
constexpr once_flag() noexcept;
since it is a constexpr your static instance will be statically initialized and we can see an example in section 30.4.4.2 Function call_once that uses a static instance:
void g() {
static std::once_flag flag2;
std::call_once(flag2, initializer());
}
Original
If we look at the documentation to std::once_flag it says:
once_flag();
Cnstructs an once_flag object. The internal state is set to indicate that no function
has been called yet.
and if we look further at the document documentation for call_once we see the following example which demonstrates how to use std::once_flag:
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void do_once()
{
std::call_once(flag, [](){ std::cout << "Called once" << std::endl; });
}
int main()
{
std::thread t1(do_once);
std::thread t2(do_once);
std::thread t3(do_once);
std::thread t4(do_once);
t1.join();
t2.join();
t3.join();
t4.join();
}
with the following expected output:
Called once
Since your question has been answered elsewhere, as an alternative to the code you posted, you can also do this instead:
// private function in anonymous namespace or something
MyClass& initMyClass() {
static MyClass c;
/* initialize c */
return c;
}
and then have clients call
MyClass& GetMyClass() {
static MyClass& c = initMyClass();
return c;
}
because static initializations are thread safe now in C++11. And then you don't have to mess with call_once or anything.
what are you trying to do? you cannot initialize std::once_flag with any value because it only has one constructor that does not take any arguments.
http://en.cppreference.com/w/cpp/thread/once_flag
once_flag(); Constructs an once_flag object. The internal state is set
to indicate that no function has been called yet.
BTW, what is the reason that you consider not initialize statics variable is a bad style?
ONCE_FLAG_INIT
EDIT: C only, not C++. Defined in <threads.h>.
I would like to have a class T that can generate only 1 instance in the whole program.
Now i know about std::unique_ptr but there are 2 problems:
it's limited to a scope ( but it's not a big issue ... )
it needs to be explicitly used, meaning that it's not part of the class or the type, it's just and handler and a special pointer, but it does not modify the design of my class.
now i would like to have class T designed in a way that not even by mistake the user can declare 2 instances in the same program and i can't rely on the fact that my user will declare an std::unique_ptr for T because i want to solve this by design.
right now i'm only thinking about how to make an implicit use of an unique_ptr in an elegant way, the problem is that i do not have any clue at the moment.
the other way around is to check if this class is handled by an unique_ptr but this check will make me lose an edge in terms of performances.
since having only 1 instance is really important, i see only 2 options in my case: 1) trying to solve this by design 2) throwing errors at compile time with some sort of check/macro.
I know that this looks trivial but with a design approach it's not, at least for me, so please help.
What you're looking for is called the Singleton pattern, and while it is widely considered by many (myself included) to be an anti-pattern, I will nonetheless show you the basic elements needed to build one.
Basically what you need to do is provide three things:
A static method which "gets" the one and only instance
A private constructor, so that nobody can ever instantiate it
(optional) A means by which the one and only instance is created before main starts
Here's the essential code:
class Singleton
{
public:
Singleton& get()
{
static Singleton me_;
return me_;
}
private:
Singleton() {};
};
I leave it to you to discover how to implement #3 above, and why you shouldn't be using a Singleton in the first place -- there are many reasons.
This is typically referred to as a Singleton.
See http://en.wikipedia.org/wiki/Singleton_pattern
The typical trick in C++ is to have a function which returns the singleton instance by reference, and make the constructor private.
Something like:
#include <iostream>
using namespace std;
class Foo
{
private:
Foo() : a(3) { a++; }
static Foo singleton;
int a;
public:
static Foo& getFoo() { return singleton; }
void doStuff() { cout<<"My a is: "<<a<<endl; }
};
Foo Foo::singleton;
int main(int argc, char** argv)
{
Foo::getFoo().doStuff();
Foo &foo = Foo::getFoo();
foo.doStuff();
//uncomment below to cause compile error
//Foo foo2;
}
Note that in real code you'll split this up into a header and a cpp file. In that case the
Foo Foo::singleton;
part must go in the cpp file.
You could have at least
static int count;
assert(count == 0);
count++;
in the constructor(s) of the singleton class. This don't ensure at compile time that your class is singleton, but at least it checks that at runtime.
And you could also make the constructor private, and have a static member function returning (once) a pointer to your instance, perhaps something like
class Singleton {
private:
Singleton() {
static int count;
assert(count == 0);
count++;
};
Singleton(Singleton&) = delete;
public:
static Singleton* the_instance() {
static Singleton* it;
if (!it) it = new Singleton();
return it;
}
};
I am using a singleton class with a thread that calls into the singleton. I was asked during a review why I used the this pointer instead of the singleton instance.
My code with the suggested changes.
class myClass : public threadWrapper
{
public:
static myClass& instance()
{
static myClass instance;
return instance;
}
// This is the callback that I have implemented
static void callback(void *me)
{
if (me != NULL)
static_cast<myClass*>(me)->doCallback();
}
// This is the suggested callback
static void callback2(void *me)
{
instance().doCallback();
}
// caller gets instance and then calls initialise()
int initialise()
{
if (initialised)
return ERROR_ALREADY_INITIALISED;
// Initialise the class
// my thread startup call
// thread wrapper class initialisation that calls pthread_create that runs the callback method with this as a parameter
// priority is a global value that difines the relative priority of the various threads.
threadWrapper::Initialise(priority, callback, this);
initialised = true;
}
private:
myClass() : initialised(false) {;}
void doCallback(void);
bool initialised;
static const int
}
So is there any significant difference in speed between the two?
The threadWrapper is mandated in the existing code base, and I'm not allowed to use boost.
My justification was that if we needed to make this not a singleton then fewer changes would be required.
The speed difference will be pretty much nonexistent.
As for code quality, Singletons are quite horrendous and I personally would chuck out both forms, especially in a threaded environment. Assuming that it's too late for that, however.
The thing is, if you're gonna pass in a pointer to the object, why not just not make that object global in the first place? And if you are, it should at least be strongly typed. And then, you're just ... wrapping a member method in a static method? Why bother? Anyone who has a pointer to the class can just call the method on it in the first place. This is just insane.
Edit: If you're stuck with the existing design, then the second version is definitely better than the first and no slower. Even if you have existing code that depends on the Singleton, then it's absolutely better to refactor what you can to not depend on it.
I am currently trying to write a threadsafe singleton (at least in terms of construction and destruction) using boost::mutex. I read that boost mutex can't be initialized statically(I lost the link where I read it, sorry) so to work around that I tried this, if threadsafety for construction and destruction is:
static T& getInstance()
{
#ifndef STATIC_VARIABLES_ARE_THREADSAFE
boost::mutex mutex;
boost::lock_guard lock(mutex);
#endif
static T instance;
return instance;
}
is that threadsafe, or should I use boost::call_once? Will boost once give me any performance benefit over this approach?
EDIT:
Okay, my first idea was obviously not correct. To clearify the question. Can a boost::mutex safely be initialized statically? Like this:
class Singleton
{
private:
static boost::mutex m_mutex;
public:
static Singleton & getInstance()
{
boost::lock_guard lock(m_mutex);
static T instance;
return instance;
}
};
Is that a working approach or is it in fact not safe to init boost::mutex statically (which is what I read)?
EDIT2:
Ah, that was the link by the way http://uint32t.blogspot.com/2007/12/you-lazy-bastard-part-1.html
Since each entry to the function will create its own lock, the lock will be completely useless; any number of threads can enter the function, lock different locks, and start messing with the static data at the same time.
You could create the lock at file (or class static) scope; this would ensure it's created in time, provided that you don't start threads before main(). However, this would also serialize entry to the function even after the static data is initialized.
Why not just define your static data at file (or class static) scope in the first place?
GCC provides thread safe initialization of static variables.
So, if you use GCC you do not need to care about proper initialization of static variables
You do need to use locking. However, the boost::mutex scheme you propose is broken since you allocate the mutex on the stack and multiple concurrent callers would each get their own mutex.
Try to use the Meyers Singleton implementation.
class MySingleton {
public:
static MySingleton& getInstance() {
static MySingleton instance;
return instance;
}
private:
MySingleton();
~MySingleton();
MySingleton(const MySingleton&)= delete;
MySingleton& operator=(const MySingleton&)= delete;
};
MySingleton::MySingleton()= default;
MySingleton::~MySingleton()= default;
// Usage
int main() {
MySingleton::getInstance();
}
More info...
The following is a well known implementation of singleton pattern in C++.
However, I'm not entirely sure whether its thread-safe.
Based upon answers to similar question asked here previously, it seems it is thread safe.
Is that so?
//Curiously Recurring Template Pattern
//Separates a class from its Singleton-ness (almost).
#include <iostream>
using namespace std;
template<class T> class Singleton {
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T& instance() {
static T theInstance;
return theInstance;
}
};
// A sample class to be made into a Singleton
class MyClass : public Singleton<MyClass> {
int x;
protected:
friend class Singleton<MyClass>;
MyClass() { x = 0; }
public:
void setValue(int n) { x = n; }
int getValue() const { return x; }
};
No, this is not thread safe because the static local is not guarded in any way. By default a static local is not thread safe. This means you could run into the following issues
Constructor for the singleton runs more than once
The assignment to the static is not guaranteed to be atomic hence you could see a partial assignment in multi-threaded scenarios
Probably a few more that I'm missing.
Here is a detailed blog entry by Raymond Chen on why C++ statics are not thread safe by default.
http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
IT IS NOT THREAD SAFE.
To become thread safe you should add a check before the lock (semaphore lock) and an other check after the lock. And then you are sure that even in simultaneous call from different threads you provide one instance.
It's not threadsafe, unless you configure your compiler to generate threadsafe code for static accesses.
However, it's better that the code be self contained, so I'd add a mutex here and there.
If you're still interest on this topic and if you're using a C++ 11 standard compiler you can find here a proposal of the singleton pattern in a multithreaded environment.