-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsingleton2.cpp
More file actions
56 lines (47 loc) · 967 Bytes
/
singleton2.cpp
File metadata and controls
56 lines (47 loc) · 967 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
54
55
#include <iostream>
#include <pthread.h>
using namespace std;
class singleton{
public:
static singleton * getInstance();
private:
singleton();
singleton(const singleton&);
singleton& operator=(const singleton&);
static singleton * instance;
static pthread_mutex_t mutex;
};
singleton::singleton()
{
}
singleton::singleton(const singleton&)
{
}
singleton& singleton::operator=(const singleton&)
{
}
///////////////////////////////////////////////////
singleton * singleton::instance = NULL;
pthread_mutex_t singleton::mutex;
singleton * singleton::getInstance()
{
if(instance == NULL)
{
pthread_mutex_lock(&mutex);
if(instance == NULL)
{
instance = new singleton();
}
pthread_mutex_unlock(&mutex);
}
return instance;
}
int main() {
singleton * pInstance1 = singleton::getInstance();
singleton * pInstance2 = singleton::getInstance();
if(pInstance1 == pInstance2)
{
cout << "Good singleton example!\n";
}
return 0;
}