单例设计模式共享数据
一、懒汉模式下多线程安全问题
class mySingle
{
public:
static mySingle* getInstance()
{
if (myInstance == nullptr)
{
std::lock_guard<std::mutex>myUniqueLock(myMutex);
if (myInstance == nullptr)
{
myInstance = new mySingle();
static mySingle::garbage mygarbage;
std::cout << "creat obj" << std::endl;
}
}
return myInstance;
}
class garbage
{
public:
~garbage()
{
if (mySingle::myInstance)
{
delete mySingle::myInstance;
myInstance = nullptr;
std::cout << "delete" << std::endl;
}
}
};
private:
mySingle() {};
std::mutex myMutex;
static mySingle* myInstance;
};
mySingle* mySingle::myInstance = nullptr;
std::mutex mySingle::myMutex;
二、std::call_once()
功能:保证函数a()只会被调用一次 ;具备互斥量这种能力,比互斥量消耗的资源更少;需要结合一个标记使用std::once_flag在函数被调用后,标志位就会标记函数已经是被调用状态。
class mySingle
{
public:
static mySingle* getInstance()
{
std::call_once(myFlag, creatInstance);
return myInstance;
}
static void creatInstance()
{
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
myInstance = new mySingle();
static mySingle::garbage mygarbage;
std::cout << "creat obj" << std::endl;
}
class garbage
{
public:
~garbage()
{
if (mySingle::myInstance)
{
delete mySingle::myInstance;
myInstance = nullptr;
std::cout << "delete" << std::endl;
}
}
};
private:
static std::once_flag myFlag;
static std::mutex myMutex;
static mySingle* myInstance;
};
mySingle* mySingle::myInstance = nullptr;
std::once_flag mySingle::myFlag;
std::mutex mySingle::myMutex;
推荐第一种写法。