#include "pch.h"
#include <iostream>
#include<list>
#include<mutex>
using namespace std;
std::mutex Mymutex;
//单例设计模式实例:
class MyCAS
{
private:
static MyCAS *m_instance;
MyCAS()
{
}
public:
static MyCAS* GetInstance()//多线程只读数据不需要加锁
{
if (m_instance == NULL) //双重否定提高效率
{
std::unique_lock<std::mutex> my_lock(Mymutex); //自动加锁
if (m_instance == NULL)
{
m_instance = new MyCAS();
static M_huishou m_hs;
cout << "m_instance 被new" << endl;
}
}
return m_instance;
}
MyCAS* print()
{
MyCAS* m = new MyCAS;
return m;
}
class M_huishou
{
public:
~M_huishou()
{
if(MyCAS::m_instance)
{
delete MyCAS::m_instance;
MyCAS::m_instance = NULL;
}
}
};
};
MyCAS * MyCAS::m_instance=NULL; //静态成员变量初始化
void func()
{
MyCAS* m = MyCAS::GetInstance();
}
int main()
{
//MyCAS m; //构造函数私有,不能直接实例对象
//MyCAS* m1 = MyCAS::GetInstance();
//MyCAS* m2 = MyCAS::GetInstance();
std::thread my_thread1(func);
std::thread my_thread2(func);
my_thread1.join();
my_thread2.join();
return 0;
}