-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.cpp
More file actions
53 lines (45 loc) · 850 Bytes
/
Singleton.cpp
File metadata and controls
53 lines (45 loc) · 850 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<bits/stdc++.h>
using namespace std;
class Singleton
{
static Singleton *instance;
static mutex mtx;
static int instanceCount;
Singleton()
{
instanceCount++;
cout<<"total instance = "<<instanceCount<<endl;
}
public:
static Singleton *getInstance()
{
if(!instance)
{
mtx.lock();
if(!instance)
{
instance = new Singleton();
}
mtx.unlock();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
int Singleton::instanceCount = 0;
mutex Singleton:: mtx;
void instance1()
{
Singleton::getInstance();
}
void instance2()
{
Singleton::getInstance();
}
int main()
{
thread first(instance1);
thread second(instance2);
first.join();
second.join();
}