循环队列应用问题(200)

D

da0306

Unregistered / Unconfirmed
GUEST, unregistred user!
我在网上找了一个循环队列的单元文件,可以应用,但好像不太实用,入队、出队多了就容易死循环,请高手帮忙找出原因?或者说出你是怎么用循环队列的?unit cirstream;interfaceuses Windows, Classes, SysUtils;type TCircleMemStream = Class(TObject) private FMemory: PChar;
FCapacity: integer;
ReadPosition: integer;
WritePosition: integer;
public constructor Create(BufferSize: integer);
destructor Destroy;
override;// function NextPosition();
function Read(Buffer: PChar;
Count: Longint): Longint;
function Write(Buffer: PChar;
Count: Longint): Longint;
function DataSize(): integer;
end;
implementationconstructor TCircleMemStream.Create(BufferSize: integer);
begin
FCapacity := 1;
while BufferSize <> 1do
begin
FCapacity := FCapacity shl 1;
BufferSize := BufferSize shr 1;
end;
GetMem(FMemory, FCapacity);
ReadPosition := 0;
WritePosition := 0;
end;
destructor TCircleMemStream.Destroy;
begin
FreeMem(FMemory);
end;
function TCircleMemStream.Read(Buffer: PChar;
Count: Longint): Longint;var Mask: integer;
roff: integer;
readsize: integer;
begin
Mask := FCapacity - 1;
Result := 0;
roff := 0;
while (ReadPosition <> WritePosition) and (Count > 0)do
begin
if WritePosition > ReadPosition then
readsize := WritePosition - ReadPosition else
readsize := FCapacity - ReadPosition;
if readsize > Count then
readsize := Count;
MoveMemory(@Buffer[roff], @FMemory[ReadPosition], readsize);
Dec(Count, readsize);
Inc(roff, readsize);
Inc(Result, readsize);
ReadPosition := (ReadPosition + readsize) and Mask;
end;
end;
function TCircleMemStream.Write(Buffer: PChar;
Count: Longint): Longint;var Mask: integer;
writesize: integer;
woff: integer;
begin
Mask := FCapacity - 1;
Result := 0;
woff := 0;
writesize := (ReadPosition - WritePosition - 1) and Mask;
//允许写入的大小 while (writesize > 0) and (Count > 0)do
begin
if ReadPosition <= WritePosition then
begin
writesize := FCapacity - WritePosition;
if ReadPosition = 0 then
Dec(writesize, 1);
end;
if writesize > Count then
writesize := Count;
MoveMemory(@FMemory[WritePosition], @Buffer[woff], writesize);
Dec(Count, writesize);
Inc(woff, writesize);
Inc(Result, writesize);
WritePosition := WritePosition + writesize and Mask;
writesize := (ReadPosition - WritePosition - 1) and Mask;
//允许写入的大小 end;
end;
function TCircleMemStream.DataSize(): integer;var Mask: integer;
begin
Mask := FCapacity - 1;
Result := (WritePosition - ReadPosition) and Mask;
end;
end.
 

Similar threads

顶部