考虑线程安全且效率高的单例C++代码
本文即考虑了线程安全,又保证了效率,代码为单例,语言为C++,代码如下:
#include <iostream> using namespace std; void Lock() { //some mutex code } void UnLock() { //some mutex code } class Singleton{ public: static Singleton* GetInstance() { if (m_Instance == NULL) // 如果已经创建了单例,那么就不用每次进去加锁了 { Lock(); if (m_Instance == NULL) { m_Instance = new Singleton(); } UnLock(); } return m_Instance; } static void DeleteInstance() { if (m_Instance) { Lock(); if (m_Instance) { delete m_Instance; m_Instance = NULL; } UnLock(); } } void TestPrint() { cout<<"lala"<<endl; } private: static Singleton* m_Instance; Singleton(){} ~Singleton(){} }; Singleton* Singleton::m_Instance = NULL; int main() { Singleton::GetInstance()->TestPrint(); return 1; }