在多线程环境下,往往开了2个以上的子线程去争夺一个对象的new。这种需要读写的代码,必然要用到互斥量。
#include "stdafx.h"
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex resource_mutex;//互斥量
MyCAS *MyCAS::m_instance = NULL;//初始为空
class MyCAS
{
public:
static MyCAS *GetInstance();//返回对象的静态成员函数
void fun();
class CGarhuishou
{//实现释放对象
public:
CGarhuishou()
{
if (MyCAS::m_instance != NULL)
{
delete MyCAS::m_instance;
MyCAS::m_instance = NULL;
}
}
};
private:
MyCAS() {}
static MyCAS* m_instance;//声明静态类类型成员变量
};
MyCAS * MyCAS::GetInstance()
{
//m_instance != NULL成立,那么肯定已经被new了
//m_instance == NULL不代表一定没被new过
if (m_instance == NULL)//双重检查
//否则,每次都需要加锁一次
//unique_lock<mutex> mymutex(resource_mutex);//自动加锁解锁
{
if (m_instance == NULL)
{
m_instance = new MyCAS();
static CGarhuishou c1;
}
}
return m_instance;
}
客户端代码如下:
nt main()
{
thread my1(mythread);
thread my2(mythread);
my2.join();
my1.join();
return 0;
}