需求
用在多线程中,保证实例的唯一性。
代码
#include <iostream>
#include<thread>
using namespace std;
class Singleton {
public:
//单例模式不允许拷贝构造函数
Singleton(Singleton& ) = delete;
//不允许重载等号
void operator=(const Singleton& ) = delete;
static Singleton* getInstance(const string& _s) {
if (self == nullptr)self = new Singleton(_s);
return self;
}
string getString()const { return s; }
void setup() const{
cout << "setup => " << s << endl;
}
void draw() const{
cout << "draw => " << s << endl;
}
protected:
string s;
static Singleton* self;//单例模式的实例指针
//实际生成实例的构造函数
Singleton(const string _s) { s = _s; }
};
//初始化实例指针
Singleton* Singleton::self = nullptr;
void _fun(string _s) {
this_thread::sleep_for(std::chrono::milliseconds(1000));//等待一秒
Singleton* s = Singleton::getInstance(_s);
cout << s->getString() << endl;
s->setup();
s->draw();
}
void fun1() {
_fun("fun1");
}
void fun2() {
_fun("fun2");
}
int main(void) {
//开两个线程
thread t1(fun1);
thread t2(fun2);
t1.join();
t2.join();
return 0;
}
结果
fun2
fun2
setup => fun2
draw => fun2
setup => fun2
draw => fun2
fun2fun1
setup => fun1setup => fun2
draw => fun2
draw => fun1
fun1fun1
setup =>
setup => fun1fun1
draw =>
fun1draw =>
fun1
fun1
setup => fun1
draw => fun1
fun1
setup => fun1
draw => fun1