forked from qinm/MemPool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemChunk.h
97 lines (88 loc) · 2.07 KB
/
MemChunk.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
96
97
#ifndef MEM_CHUNK_H
#define MEM_CHUNK_H
#include <iostream>
#include <windows.h>
typedef CRITICAL_SECTION MUTEXTYPE;
#define INITMUTEX(hMutex) InitializeCriticalSection(&hMutex)
#define DELMUTEX(hMutex) DeleteCriticalSection(&hMutex)
#define LOCK(hMutex) EnterCriticalSection(&hMutex)
#define UNLOCK(hMutex) LeaveCriticalSection(&hMutex)
struct MemBlock;
struct BlockHeader{
MemBlock *next;
int size;
};
typedef struct MemBlock{
BlockHeader header;
char pBuff;
}MemBlock,*pMemBlock;
class MemChunk{
public:
typedef MemChunk * pMemChunk;
MemChunk(size_t size,int count):_size(size),_count(count){
INITMUTEX(_hMutex);
pFreeList=CreatBlock();
pFreeList->header.size=_size;
pFreeList->header.next=NULL;
pMemBlock pBlock=pFreeList;
for(int i=0;i<count-1;++i){
pBlock=CreatBlock();
if(pBlock){
pBlock->header.next=pFreeList->header.next;
pFreeList->header.next=pBlock;
}
}
}
~MemChunk(){
size_t tmpCnt=0;
pMemBlock pBlock;
while(pFreeList!=NULL){
pBlock=pFreeList;
pFreeList=pFreeList->header.next;
FreeBlock(pBlock);
++tmpCnt;
}
DELMUTEX(_hMutex);
if(tmpCnt!=_count)
std::cout<<"there are still "<<_count-tmpCnt<<"blocks with size "<<_size<<" bytes need to free"<<std::endl;
// std::cout<<"MemChunk with size "<<_size<<" bytes has been free"<<std::endl;
}
size_t getSize(){
return _size;
}
bool hasFree(){
return pFreeList!=NULL;
}
void *GetChunk(){
LOCK(_hMutex);
pMemBlock pBlock=pFreeList;
pFreeList=pFreeList->header.next;
UNLOCK(_hMutex);
return &pBlock->pBuff;
}
void FreeChunk(pMemBlock pBlock){
LOCK(_hMutex);
pMemBlock pTmp=pFreeList;
pFreeList=pBlock;
pFreeList->header.next=pTmp;
UNLOCK(_hMutex);
return;
}
private:
pMemBlock CreatBlock(){
pMemBlock pBlock=(pMemBlock)::malloc(sizeof(BlockHeader)+_size);
pBlock->header.size=_size;
pBlock->header.next=NULL;
return pBlock;
}
void FreeBlock(pMemBlock pBlock){
::free(pBlock);
pBlock=NULL;
}
private:
size_t _size; //chunk size
size_t _count; //chunk numbers
MUTEXTYPE _hMutex; //mutex;
pMemBlock pFreeList; //real block list
};
#endif