#include<iostream>
using namespace std;
//懒汉模式
#include<thread> //线程库
#include<mutex> //锁
class singleton
{
public:
static singleton* getinstance()
{
if (_ps == nullptr)
{
_mtx.lock(); //加锁
if (_ps == nullptr)
{
_ps = new singleton;
}
_mtx.unlock(); //解锁
}
return _ps;
}
private:
singleton()
{
for (int i = 0; i < 10000000; i++)
{
int b = i;
}
}
singleton(const singleton& s); //封死拷贝构造
static singleton* _ps;
static mutex _mtx;
};
singleton* singleton::_ps = nullptr;
mutex singleton::_mtx;
void fun()
{
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
}
int main()
{
singleton* ps = singleton::getinstance();
delete ps;
thread t1(fun); //创建t1 t2两个线程;
thread t2(fun);
t1.join();
t2.join();
return 0;
}
c++单例模式(懒汉模式)
最新推荐文章于 2024-06-16 00:26:19 发布