feat: thread-safe Singleton
parent
8e7f3d1bb0
commit
45bfeca806
|
@ -1,9 +1,42 @@
|
|||
#include <cstdlib>
|
||||
#include <iomanip>
|
||||
#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[]) {
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue