-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.cpp
112 lines (99 loc) · 2 KB
/
singleton.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <pthread.h>
/**
* c++11中是线程安全的,在之前的版本不是线程安全的
*/
/*
class Singleton{
public:
static Singleton& getInstance(){
static Singleton singleton;
return singleton;
}
};
*/
/**
* 线程不安全
*/
/*
class Singleton{
public:
Singleton(){}
static Singleton* getInstance();
private:
static Singleton* p;
};
Singleton* Singleton::p = NULL;
Singleton* Singleton::getInstance(){
if (p == NULL)p = new Singleton();
return p;
}
*/
/**
* 懒汉模式
*/
class Singleton{
public:
//Singleton(){
//pthread_mutex_init(&mutex, NULL);
//}
static Singleton* getInstance();
private:
Singleton(){}
static pthread_mutex_t mutex;
static Singleton* p;
};
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton* Singleton::p = NULL;
Singleton* Singleton::getInstance(){
if (p == NULL){
pthread_mutex_lock(&mutex);
if (p == NULL)p = new Singleton();
pthread_mutex_unlock(&mutex);
}
return p;
}
/**
* 懒汉模式2
*/
/*
class Singleton{
public:
Singleton(){
//pthread_mutex_init(&mutex, NULL);
}
static Singleton* getInstance();
private:
static pthread_mutex_t mutex;
};
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton* Singleton::getInstance(){
pthread_mutex_lock(&mutex);
static Singleton p;
pthread_mutex_unlock(&mutex);
return &p;
}
*/
/**
* 恶汉模式
*/
/*
class Singleton{
public:
Singleton(){};
static Singleton* getInstance();
private:
static Singleton* p;
};
Singleton* Singleton::p = new Singleton();
Singleton* Singleton::getInstance(){
return p;
}
*/
int main(){
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
printf("s1 addr=%p, s2 addr=%p\n",s1, s2);
return 0;
}
//g++ -O singleton.cpp --std=c++11