- 论坛徽章:
- 0
|
template<class T>
class RingQueue {
public:
RingQueue() {
cout << "RingQueue::ctor" << endl;
};
virtual ~RingQueue() {
cout << "RingQueue::destory" << endl;
};
void InitQueue() {
Push_Count = 0;
Push_Index = 0;
Pop_Count = 0;
Pop_Index = 0;
memset(List, 0, sizeof (List));
}
bool Push(const T& 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;
}
T Pop() {
T 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;
}
long size() {
return this->Push_Count - this->Pop_Count;
}
private:
RingQueue(const RingQueue& orig);
T List[524288 * 2]; //2^19 4M�ռ�
const static unsigned long Max_Count = 524288 * 2;
const static unsigned long High_Index = 524288 * 2 - 1;
unsigned long Push_Count;
unsigned long Push_Index;
unsigned long Pop_Count;
unsigned long Pop_Index;
};
---------------------------------------------------------无奈的分割线
之前的“编译器乱序优化”,我开始说Pop()函数里改成if (Push_Count > Pop_Count)可以避免,想到溢出时的情况就不成立了,改成if (Push_Count - Pop_Count > 0)就好,但Push函数也会有类似的问题,就是在环形队列满的时候,所以我改成如下:
bool Push(const T& AData) {
if (size() < Max_Count) {//环形队列不满
if(List[Push_Index] != NULL)//这时候元素还没被pop出去
return false;
List[Push_Index] = AData;
Push_Count++;
if (Push_Index == High_Index)
Push_Index = 0;
else
Push_Index++;
return true;
} else
return false;
}
T Pop() {
T result = NULL;
if (size() > 0) {//环形队列不为空
result = List[Pop_Index];
Pop_Count++;
if (Pop_Index == High_Index)
Pop_Index = 0;
else
Pop_Index++;
List[Pop_Index] = NULL;//已经pop的元素清空,放到这里防止编译器跟Pop_Count++;语句优化成序列颠倒
}
return result;
}
|
|