线程安全的单例模式

2020-09-02  本文已影响0人  孤独患者_d589

下列程序是基于多线程下的互斥量锁进行的单例模式。

<code>

class SingleInstance

{

public:

static SingleInstance* GetInstance();

static void deleteInstance();

void Print();

private:

SingleInstance();

~SingleInstance();

SingleInstance(const SingleInstance& signal);

const SingleInstance &operator=(const SingleInstance& signal);

private:

static SingleInstance* m_instance;

static mutex mymutex;

};

SingleInstance* SingleInstance::m_instance = nullptr;

mutex SingleInstance::mymutex;

SingleInstance* SingleInstance::GetInstance()

{

if (!m_instance)

{

unique_lock<mutex>lock(mymutex);

if (!m_instance)

{

m_instance = new SingleInstance();

}

}

return m_instance;

}

void SingleInstance::deleteInstance()

{

unique_lock<mutex>lock(mymutex);

if (m_instance)

{

delete m_instance;

m_instance = nullptr;

}

}

void SingleInstance::Print()

{

cout << "我的实例内存地址是:" << this << endl;

}

SingleInstance::SingleInstance()

{

std::cout << "构造函数" << std::endl;

}

SingleInstance::~SingleInstance()

{

std::cout << "析构函数" << std::endl;

}

void test0()

{

cout << "test0的线程id为: " << this_thread::get_id() << endl;

for (int i = 0; i < 5; ++i)

{

SingleInstance* single = SingleInstance::GetInstance();

single->Print();

}

}

void test1()

{

cout << "test1的线程id为: " << this_thread::get_id() << endl;

for (int i = 0; i < 5; ++i)

{

SingleInstance* single1 = SingleInstance::GetInstance();

single1->Print();

}

}

</code>

上一篇下一篇

猜你喜欢

热点阅读