本文即考虑了线程安全,又保证了效率,代码为单例,语言为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;
}
原文链接: https://www.cnblogs.com/lihaozy/archive/2012/11/21/2781603.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/70146
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!