-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmempool.h
95 lines (95 loc) · 2.56 KB
/
mempool.h
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
#ifndef MGNR_MEMPOOL
#define MGNR_MEMPOOL
#include <mutex>
#include <atomic>
namespace mgnr{
template<typename T>
class mempool_block{
T * freed;
std::mutex locker;
std::atomic<int> rnum,//引用计数器
malloced,used;
public:
inline void pickup(){
rnum++;
}
inline void giveup(){
rnum--;
if(rnum==0){
delete this;
return;
}
}
mempool_block(){
malloced=0;
used=0;
freed=NULL;
rnum=1;
}
~mempool_block(){
T * it1;
T * it=freed;
while(it){
it1=it;
it=it->next;
delete it1;
}
#ifdef DEBUG
int mn=malloced;
int un=used;
printf("malloc:%d\tused:%d\n",mn,un);
#endif
}
T * get(){
used++;
locker.lock();
if(freed){
T * r=freed;
freed=freed->next;
locker.unlock();
return r;
}else{
locker.unlock();
malloced++;
return new T;
}
}
void del(T * f){
locker.lock();
f->next=freed;
freed=f;
locker.unlock();
used--;
}
};
template<typename T>
class mempool{
protected:
mempool_block<T> * parpool;
std::atomic<int> malloced,used;
public:
mempool(){
malloced=0;
used=0;
static mempool_block<T> gbpool;
parpool=&gbpool;
}
~mempool(){
#ifdef DEBUG
int mn=malloced;
int un=used;
printf("malloc:%d\tused:%d\n",mn,un);
#endif
}
T * get(){
malloced++;
used++;
return parpool->get();
}
void del(T * f){
used--;
parpool->del(f);
}
};
}
#endif