-
Notifications
You must be signed in to change notification settings - Fork 0
/
MBuffer.h
114 lines (105 loc) · 2.16 KB
/
MBuffer.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#pragma once
#include "MyHeader.h"
//环形队列缓冲区
template<class T>
class CMBuffer
{
public:
CMBuffer(UINT len):m_Pos0(0),m_Pos1(0),m_DataLen(0)
{
m_BufferLen = len;
m_pBuffer = new T[len];
if(pthread_mutex_init(&m_Mutex, NULL) < 0)
exit(0);
}
virtual ~CMBuffer()
{
delete []m_pBuffer;
m_pBuffer = NULL;
pthread_mutex_destroy(&m_Mutex);
}
int Add(const T* pSrc,UINT len)//返回实际添加的数据长度
{
UINT i = 0;
pthread_mutex_lock(&m_Mutex);
while (i < len)
{
if (-1 == Add(pSrc[i]))//添加失败,缓冲区满
{
break;
}
else
{
++i;
}
}
pthread_mutex_unlock(&m_Mutex);
return i;
}
int Read(T* pDest, UINT len)
{
UINT i = 0;
while (i < len)
{
if (-1 == Read(pDest++))
{
break;
}
else
{
++i;
}
}
return i;
}
int IsEmpty()
{
return ( 0 == m_DataLen);
}
int IsFull()
{
return (m_DataLen == m_BufferLen);
}
UINT GetDataLen()
{
return m_DataLen;
}
UINT GetCapacity()
{
return m_BufferLen;
}
private:
int Add(T data) //如果缓冲区满,返回-1,否则返回1
{
if (m_DataLen == m_BufferLen)//缓冲区已满
return -1;
else
{
m_pBuffer[m_Pos1++] = data;
m_Pos1 = m_Pos1 % m_BufferLen;
++m_DataLen;
return 1;
}
}
int Read(T* data)
{
if (m_DataLen == 0)
return -1;
else
{
pthread_mutex_lock(&m_Mutex);
*data = m_pBuffer[m_Pos0++];
m_Pos0 = m_Pos0 % m_BufferLen;
--m_DataLen;
pthread_mutex_unlock(&m_Mutex);
return 1;
}
}
private:
T* m_pBuffer;
UINT m_Pos0;
UINT m_Pos1;
UINT m_DataLen;
UINT m_BufferLen;
pthread_mutex_t m_Mutex;
};