1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <mutex> 6 #include <thread> 7 using namespace std; 8 9 #define ll long long 10 11 const int maxn=1e5+10; 12 13 class Singleton { 14 public: 15 static Singleton* getInstance() { 16 if (instance == nullptr) { 17 lock_guard<mutex> lock(mtx); 18 if (instance == nullptr) 19 instance = new Singleton(); 20 } 21 return instance; 22 } 23 24 void dosomething() { 25 } 26 27 static void destoryInstance() { 28 if (instance != nullptr) { 29 delete instance; 30 instance = nullptr; 31 } 32 } 33 private: 34 Sinleton(const Singleton&) = delete; 35 Singleton& operator=(const Singleton&) = delete; 36 37 static Singleton *instance; 38 static mutex mtx; 39 }; 40 41 void threadFunc(int id) 42 { 43 cout << "thread " + to_string(id) << endl; 44 Singleton *s = Singleton::getInstance(); 45 s -> dosomething(); 46 } 47 48 Singleton * Singleton::instance = nullptr; 49 mutex Singleton::mtx; 50 51 int main() 52 { 53 thread t1(threadFunc, 1); 54 thread t2(threadFunc, 2); 55 thread t3(threadFunc, 3); 56 t1.join(); 57 t2.join(); 58 t3.join(); 59 Singleton::destoryInstance(); 60 return 0; 61 }