-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.cpp
More file actions
37 lines (32 loc) · 900 Bytes
/
Singleton.cpp
File metadata and controls
37 lines (32 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<bits/stdc++.h>
using namespace std;
class Singleton{
static Singleton* instance;
static mutex mtx;
// Private constructor to prevent instantiation
Singleton() {
cout << "Singleton instance created." << endl;
}
public :
// Static method to get the instance of the Singleton class
static Singleton* getInstance() {
if(instance == nullptr) {
lock_guard<mutex> lock(mtx); // Ensure thread safety
if(instance == nullptr) {
// to ensure that only one instance is created
instance = new Singleton();
}
return instance;
}
else {
return instance;
}
}
};
Singleton* Singleton::instance = nullptr;
mutex Singleton::mtx;
int main(){
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
cout << (s1 == s2) << endl;
}