Huy Vũ Quang

29 bundles
3 filesa month ago
2

Template Singleton

Singleton.h

1234567891011121314151617181920212223242526272829
#ifndef _SINGLETON_H_ #define _SINGLETON_H_ template<typename T> class Singleton { public: static T& instance(); Singleton(const Singleton&) = delete; Singleton(Singleton&&) = delete; Singleton& operator= (const Singleton) = delete; Singleton& operator= (Singleton&&) = delete; protected: Singleton() {}; ~Singleton() {}; }; #include <memory> template<typename T> T& Singleton<T>::instance() { static const std::unique_ptr<T> instance(new T()); return *instance; } #endif

ThreadSafeSingleton

12345678910111213141516171819202122232425262728293031323334353637383940
#include <iostream> #include <thread> #include "Singleton.h" class CounterSingleton final : public Singleton<CounterSingleton> { atomic<int> mCount; public: void initialize() { atomic_init(&mCount, 0); } void increase() { mCount += 1; } int get() { return mCount; } }; void counterTask(int times) { for (int i = 0; i < times; i++) { CounterSingleton::instance().increase(); } } int main() { CounterSingleton::instance().initialize(); thread counterThread1(counterTask, 10000); thread counterThread2(counterTask, 10000); counterThread1.join(); counterThread2.join(); cout << CounterSingleton::instance().get() << endl; return 0; }

main.cpp

12345678910111213141516171819202122232425262728293031323334353637
#include <iostream> #include "Singleton.h" using namespace std; class HelloSingleton final : public Singleton<HelloSingleton> { public: void sayHello() { cout << "Hello Singleton" << endl; } }; class CounterSingleton final : public Singleton<CounterSingleton> { int mCount = 0; public: void increase() { mCount += 1; } int get() { return mCount; } }; int main() { HelloSingleton::instance().sayHello(); CounterSingleton::instance().increase(); CounterSingleton::instance().increase(); cout << CounterSingleton::instance().get() << endl; return 0; }