feat: thread-safe Singleton

This commit is contained in:
Michael Mandl 2024-03-14 11:04:04 +01:00
parent 8e7f3d1bb0
commit 45bfeca806
Signed by: mandlm
GPG key ID: 4AA25D647AA54CC7

View file

@ -1,9 +1,42 @@
#include <cstdlib> #include <cstdlib>
#include <iomanip>
#include <iostream> #include <iostream>
#include <mutex>
class Singleton {
private:
static Singleton *singleton;
static std::mutex mutex;
Singleton() = default;
public:
Singleton(const Singleton &other) = delete;
Singleton &operator=(const Singleton &) = delete;
static Singleton *GetInstance() {
std::lock_guard<std::mutex> lock(mutex);
if (singleton == nullptr) {
singleton = new Singleton();
}
return singleton;
}
};
Singleton *Singleton::singleton = nullptr;
std::mutex Singleton::mutex;
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
std::cout << "Singleton" << std::endl; std::cout << "Singleton" << std::endl;
auto singleton1 = Singleton::GetInstance();
auto singleton2 = Singleton::GetInstance();
std::cout << std::setw(20) << "Singleton 1: " << singleton1 << std::endl;
std::cout << std::setw(20) << "Singleton 2: " << singleton2 << std::endl;
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }