beginner's C++ thread-safe singleton design - c++

I wish to create a static Class object which should stay in the memory while the program is running. The object needs to be initialized only once by the init function and the output function will be called in a static method always. Does my code make sense and is it thread-safe?
class Singleton
{
public:
static void init(const int value)
{
static Singleton inst;
inst.Value = value;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
int main()
{
int inputValue = 10;
Singleton::init(inputValue);
cout << Singleton::prnValue();
return 0;
}
New Edit:
Or can I try like this then?
class Singleton
{
public:
static Singleton& init(const int value)
{
static Singleton inst;
inst.Value = value;
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
Addition:
Meyer's singleton example look like
class Singleton
{
public:
static Singleton& init()
{
static Singleton inst;
return inst;
}
private:
Singleton() {};
};
So Isn't my code consistent with Meyer's example?
Try4:
How about this?
class Singleton
{
public:
static Singleton& init(int value)
{
static Singleton inst(value);
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton(value)
{
Value = value;
}
int Value;
};
Added comment:
How to pass argument in a singleton
seems to provide the same answer as Try4.

Abandon Singleton and make Value a const global variable initialized with a helper function.
Example:
// anonymous namespace to bind the global to this file to prevent the static
// initialization order fiasco
namespace
{
const int Value = ReadIniFile("section", "key", default_value);
}
But what if you need to use this variable in other files? The best advice I've got is don't. But if you must, the static initialization order fiasco needs to be overcome. Here's a quick way to do that that is similar to what you've seen so far:
// Lazy loader function similar to Meyers Singleton
int Value()
{
static int value = ReadIniFile("section", "key", default_value);
return value;
}
Usage:
me_function_need_Value(Value());
This ensures that Value is initialized before anyone can try to use it no matter which file in your project needs it. Unfortunately it's now hard to figure out when it goes out of scope, so the problem doesn't really go away. It's just moved from the start of the program to the end where it is a little more manageable. See Destruction order of static objects in C++ .
Ensure no one uses Value after main exits and you'll be safe. Still, use with caution.

Related

Singleton Class not working into multiple files

Say I have this code:
#include <iostream>
using namespace std;
class Something
{
int field1;
static Something *nill;
static bool initialized;
static void initialize() {
if (initialized)
return;
initialized = true;
}
public:
static Something* Nill()
{
initialize();
return nill;
}
static Something* Singleton(int field1)
{
initialize();
Something *ret = new Something();
ret->field1 = field1;
return ret;
}
}
Something* Something::nill = new Something();
bool Something::initialized = false;
int main(void)
{
Something *smth = something->Nill();
return 0;
}
Why isn't 'Something' a Singleton Class, and how could I make it one? Also how could I split this code into 2 files a .h and a .cpp? I had problems with that because I have some global variables here and I don't know how to use them in other files..
This is not a singleton class. Singleton class implies that in any given time you cannot have more than 1 instance of the class. In your example, you're not only creating a new instance but even return new class objects in its methods.
Make a default constructor protected (copy or move constructors too if you really want to be sure it's as singleton). Then use your static 'nill' as shown below:
class Something {
protected:
Something() = default;
...
int main() {
Something::nill->Nill();
...
P.s. Are you sure you need a singleton? Your methods say opposite.

Thread Safe Singleton Class - Am I doing this Right?

I am creating a system state class that needs be thread safe in reading/writing. I am implementing it using the Singleton Design Pattern.
I have based it off of pointers from these Stackoverflow questions:
Singleton: How it Should be Used
C++ Singleton Design Pattern
Here is a condensed example of my code. Essentially it is just some state variables I need to keep track of and share across several threads. I know for a fact there will only ever needs be one state instance and I know that it needs to thread safe and constant. Will this implementation ensure that?
// System_State.h
class System_State
{
public:
static System_State &getInstance()
{
static System_State stateInstance;
return stateInstance;
}
System_State(System_State const&) = delete;
void operator=(System_State const&) = delete;
// Example Setter with mutex guard
void setWifiConnectedStatus(uint8_t _status)
{
std::lock_guard<std::mutex> lock(mtx);
Wifi.ConnectedStatus = _status;
}
private:
System_State()
{
initializeState();
}
void initializeState();
std::mutex mtx;
static struct WifiService
{
uint8_t ConnectedStatus;
std::string CurrentConnection;
std::string SavedNetworks;
std::string AvailableNetworks;
std::string ForgetNetwork;
std::string ConnectTo;
std::string DisconnectFrom;
} Wifi;
static struct ScanService
{
std::string PerformScan;
std::string ScanStatus;
uint8_t ScanProgress;
} Scan;
static struct UploadDataService
{
std::string PerformUpload;
uint8_t UploadProgress;
uint8_t ItemsWaitingToBeUploaded;
} UploadData;
static std::string LEDControlBrightness;
static uint8_t BatteryPercentage;
};
And here is some example main
//main.cpp
#include <thread>
void loop1()
{
System_State state = System_State::getInstance();
while(true)
{
//do randomness with state
}
}
void loop2()
{
System_State state2 = System_State::getInstance();
while(true)
{
//do randomness with state2
}
}
int main()
{
std::thread t1(loop1);
std::thread t2(loop2);
// do and join and all that!
return 0;
}
Yours is not idiomatic singleton, because it is still prone to so-called "static initialization order fiasco".
An idiomatic singleton doesn't have a static class member, instead it's instance function looks like
static MySingleton& instance() {
static MySingleton the_ton;
return the_ton;
}
More on the fiasco: static initialization order fiasco
No, this may not work in a more complex case, but not for thread-safety reason, but because of the undefined behavior of static object initialization.
Let's say that your object here:
static System_State stateInstance;
requires another static object that you retrieve with another static getInstance. You have no assurance that this will return a valid/constructed object.
If you can ensure that this object doesn't require another static object, then you should be fine. But this is the issue with lots of singleton constructions, you have to balance when it is constructed and thread-safety.

How to prevent a caller of a method from storing the result in C++

Assume I have a Singleton class. How can I prevent callers from being able to store the result of the call to getInstance() method?
I need this, since the instance of the singleton can be modified during execution and any stored instance in other classes will be invalidated. My solution would be to force all the callers to call getInstance() every time when they want to use the instance of the Singleton.
class Singleton
{
private:
static Singleton* instance;
private:
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = nullptr;
Singleton* Singleton::getInstance()
{
if (instance == nullptr)
{
instance = new Singleton();
}
return instance;
}
class A
{
private:
Singleton* m_singleton;
public:
A()
: m_singleton(Singleton::getInstance()) //This should not be possible
{
}
};
int main()
{
A a;
return 0;
}
How can I achieve this?
You cannot. If your getInstance() returns a pointer or reference, there is no way to prevent the result from being copied into some variable, the same way as you cannot prevent a result of type int or double from being copied.
You could, however, make the functions the singleton provides static:
class SomeSingleton
{
public:
static void foo();
private:
// deleting copy constructor and assignment operator...
static SomeSingleton* getInstance();
};
void SomeSingleton::foo()
{
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
So you enforce usage like this:
SomeSingleton::foo();
Some might even consider it more comfortable to use than
SomeSingleton::getInstance().foo();
By the way: This aproach makes it possible to protect you from race conditions, too, if multi-threading is or gets an issue:
class SomeSingleton
{
public:
static void foo();
private:
static std::mutex mutex; // <- add a mutex!
static SomeSingleton* getInstance();
static void exchange();
};
void SomeSingleton::foo()
{
// this must be added whenever the singleton is used...
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
void SomeSingleton::exchange()
{
// ... or the singleton instance is re-asigned
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* newInstance = new SomeSingleton();
delete instance;
instance = newInstance;
}
My solution is a wrapper with overloaded -> operator like in smart pointers which calls getInstance() inside:
class Singleton {
friend SingletonWrapper;
private:
static Singleton * getInstance() {...}
public:
void foo() {}
};
class SingletonWrapper {
public:
Singleton * operator->() {
return Singleton::getInstance();
}
};
int main() {
SingletonWrapper w;
w->foo();
}
First of all I wouldn't suggest using pointers for singletons. This ("Meyer Singleton") is a much better approach.
static SingletonDatabase &get() {
static SingletonDatabase db;
return db;
}
Also storing the singleton is kind of a bad idea, as with the storing you validate the initial idea / purpose behind the singleton: You are making copies, thus the singleton is not the "sole" instance of the class.
Anyway a great solution to your problem would be to use some kind of signal/slot system. (Qt / Boost library) Upon change you can emit the singal, which is then "caught" by all instances and the actualize the values.
Boost Signals / Slots
Qt Signals Slots
I Hope this helps :)
Use volatile to declare the singleton variable. This will force the compiler to always check for it
class Singleton
{
private:
static volatile Singleton* instance;
private:
Singleton();
public:
static volatile Singleton* getInstance();
};

Overcoming static initialization order fiasco when a singleton object is involved

I have a singleton class defined in file x.h
class x
{
public:
static x* x_instance;
static x* create_x_instance
{
if(!x_instance)
x_instance = new x;
return x_instance;
}
void someMemberFunction()
private:
x() { //some code}
};
extern x *x_interface;
In x.cpp I have the following:
x *x::x_instance = 0;
x *x_interface = x::create_x_instance();
In y.cpp, in the constructor of a another singleton class, I have
x_interface->someMemberFunction();
I get a seg fault because y gets initialized before x. What is the correct way to solve this? I have read many articles on this, but I am still confused.
Just to be clear, using a static member of a static function avoids initialization order problems:
class x
{
public:
static x* get_instance()
{
static x* theInst = new x;
return theInst;
}
void someMemberFunction();
private:
x() { //some code}
};
Later code gets x like this:
x* handle = x::get_instance();
The above is minimal, it should be further improved to manage x lifetime. It might be better to just have theImpl be a static x rather than pointer-to-x, and get_instance() return a reference instead of a pointer.
allow the compiler to generate the singleton on first use by initialising it as a static member of a static function.
Additionally, you can go further and give your singleton object value semantics with zero cost while offering may benefits:
class x
{
struct impl
{
void someMemberFunction() {
}
};
static impl& get_impl() {
static impl _{};
return _;
}
public:
void someMemberFunction()
{
return get_impl().someMemberFunction();
}
};
int main()
{
auto a = x();
a.someMemberFunction();
}
Why do you need a x_interface as global or static instance as you can get the instance of class x from anywhere at any time using static method : create_x_instance ?
I think best way to use it in class y is as :
(x::create_x_instance())->someMemberFunction();

Is the typical C++ implementation of Factory class flawed?

I have the need to implement factory class in C++, but when I was thinking about that, I found one big problem that I couldn't solve, and I found out, that all factory implementation examples around are flawed in the same way. I'm probably the one who is wrong, but please tell me why.
So here is simple "typical" factory implementation, it allows me to register new objects without changing the Factory class.
//fruit.h
class Fruit
{
protected :
int count;
public :
Fruit(int count) : count(count) {}
virtual void show() = 0;
};
// factory.h
/** singleton factory */
class Factory
{
typedef Fruit* (*FruitCreateFunction)(int);
static Factory* factory;
std::map<std::string, FruitCreateFunction> registeredFruits;
public :
static Factory& instance()
{
if (factory == NULL)
factory = new Factory();
return *factory;
}
bool registerFruit(const std::string& name, Fruit* (createFunction)(int))
{
registeredFruits.insert(std::make_pair(name, createFunction));
return true;
}
Fruit* createFruit(const std::string& name, int count)
{
return registeredFruits[name](count);
}
};
//factory.cpp
Factory* Factory::factory = NULL;
//apple.h
class Apple : public Fruit
{
static Fruit* create(int count) { return new Apple(count); }
Apple(int count) : Fruit(count) {}
virtual void show() { printf("%d nice apples\n", count); };
static bool registered;
};
// apple.cpp
bool Apple::registered = Factory::instance().registerFruit("apple", Apple::create);
//banana.h
class Banana : public Fruit
{
static Fruit* create(int count) { return new Banana(count); }
Banana(int count) : Fruit(count) {}
virtual void show() { printf("%d nice bananas\n", count); };
static bool registered;
};
// banana.cpp
bool Banana::registered = Factory::instance().registerFruit("banana", Banana::create);
// main.cpp
int main(void)
{
std::vector<Fruit*> fruits;
fruits.push_back(Factory::instance().createFruit("apple", 10));
fruits.push_back(Factory::instance().createFruit("banana", 7));
fruits.push_back(Factory::instance().createFruit("apple", 6));
for (size_t i = 0; i < fruits.size(); i++)
{
fruits[i]->show();
delete fruits[i];
}
return 0;
}
Ok, this code looks fancy and it works, but here comes the but:
The C++ standard doesn't allow me to define the order in which global (static) variables will be defined.
I have 3 static variables here
Apple::registered;
Banana::registered;
Factory::factory;
The Factory::factory pointer needs to be defined to NULL before the Apple(or Banana)::registered variable, or the Factory::instance method will work with uninitialized value, and behave unpredictably.
So, what am I not getting here? Is the code really working only by an accident? If so, how should I solve the issue?
All global POD data is guaranteed to be initialized to a constant value before any initializers run.
So at the start of your program, before any of the register calls are made and before main is run, the pointer is NULL and all of the bools are false, automatically. Then the initializers run, including your register calls.
Edit: Specifically, from the standard (3.6.2.2: Initialization of non-local objects):
Together, zero-initialization and
constant initialization are called
static initialization; all other
initialization is dynamic
initialization. Static initialization
shall be performed before any dynamic
initialization takes place.
All static variables are initialized before the program begins to run. They are set at compile time and baked right into the executable.
The only issue arises when one static variable depends on another:
In a.hpp:
static int a = 1;
in b.hpp:
extern int a;
static int b = a;
The order in which static variables are initialized is not well defined, so b may or may not be 1 in this example. As long as your variables don't depend on each other, you're fine. Furthermore, is you don't give an initial value, static members are set to zero by default.
I've tended to see the 'instance' method of Factory implemented as follows:
static Factory& instance()
{
static Factory *factory = new Factory();
return *factory;
}
However, the point is that all access to the instance runs through the static instance method. The calls to register the two fruit classes for example use Factory::instance() to obtain the singleton which will guarantee that the initializer for Factory::factory has executed. In my posted alternative implementation the static initialization only occurs the first time the method is called.
The possible issues with Apple::registered and Banana::registered depend on where they might be used from. In the posted code they aren't used at all. If used only within apple.cpp and banana.cpp respectively then there is no issue with order of initialization.