环形一读一写队列中,不需要担心unsigned long溢出问题,因为溢出后自动回归,相减值还会保留。
示例一(注:Max_Count 必须为 2 的指数,即:2, 4, 8, 16...):
// 队列尺寸
#define Max_Count 4096
#define Max_Mask 4095 // = Max_Count - 1
// 变量
void* List[Max_Count];
unsigned long Push_Count;
unsigned long Pop_Count;
// 初始化队列
void InitQueue()
{
Push_Count = 0;
Pop_Count = 0;
memset(List, 0, sizeof(List));
}
// 加入
bool Push(void* AData)
{
if (Push_Count - Pop_Count < Max_Count)
{
List[Push_Count & Max_Mask] = AData;
Push_Count++;
return true;
}
else
return false;
}
// 取出
void* Pop()
{
// 初始化
void* result = NULL;
// 判断是否为空
if (Push_Count != Pop_Count)
{
result = List[Pop_Count & Max_Mask];
Pop_Count++;
}
// 返回结果
return result;
}
示例二(注:Max_Count >= 2):
// 队列尺寸
#define Max_Count 4096
#define High_Index 4095 // = Max_Count - 1
// 变量
void* List[Max_Count];
unsigned long Push_Count;
unsigned long Push_Index;
unsigned long Pop_Count;
unsigned long Pop_Index;
// 初始化队列
void InitQueue()
{
Push_Count = 0;
Push_Index = 0;
Pop_Count = 0;
Pop_Index = 0;
memset(List, 0, sizeof(List));
}
// 加入
bool Push(void* AData)
{
if (Push_Count - Pop_Count < Max_Count)
{
List[Push_Index] = AData;
Push_Count++;
if (Push_Index == High_Index)
Push_Index = 0;
else
Push_Index++;
return true;
}
else
return false;
}
// 取出
void* Pop()
{
// 初始化
void* result = NULL;
// 判断是否为空
if (Push_Count != Pop_Count)
{
result = List[Pop_Index];
Pop_Count++;
if (Pop_Index == High_Index)
Pop_Index = 0;
else
Pop_Index++;
}
// 返回结果
return result;
}