我的简单循环缓冲区无法正常工作

时间:2015-10-08 11:02:41

标签: c# circular-buffer

我正在尝试实现简单的循环缓冲区。

out.close();

生成测试的代码:

class MyCircularBuffer
{
    byte[] Buffer = null;

    private Object BufferLock = new object();

    int readIndex = 0;
    int writeIndex = 0;

    int SpaceBetweenIndexes
    {
        get;
        set;
    }

    int ReadIndex
    {
        get
        {
            return readIndex;
        }
        set
        {
            readIndex = value;
            CalculateSpaceBetweenIndexes();
        }
    }

    void CalculateSpaceBetweenIndexes()
    {
        if (readIndex <= writeIndex)
        {
            SpaceBetweenIndexes = writeIndex - readIndex;
        }
        else
        {
            SpaceBetweenIndexes = Length - (readIndex - writeIndex);
        }
    }

    int WriteIndex
    {
        get
        {
            return writeIndex;
        }
        set
        {
            writeIndex = value;
            CalculateSpaceBetweenIndexes();
        }
    }

    int Length;

    int Count
    {
        get
        {
            lock(BufferLock)
            {
                return Buffer.Count();
            }
        }
    }

    public MyCircularBuffer(int length)
    {
        Buffer = new byte[length];
        this.Length = length;
        ReadIndex = 0;
        WriteIndex = 0;
    }

    public byte ReadByte()
    {
        while (SpaceBetweenIndexes <= 1)
        {
            CalculateSpaceBetweenIndexes();
        }

        ReadIndex++;

        if (ReadIndex < Length)
        {
            Console.WriteLine("Read from index " + (ReadIndex-1) + " value " + this[ReadIndex - 1]);
            return this[ReadIndex - 1];
        }
        else
        {
            ReadIndex = 0;
            Console.WriteLine("Read from index " + (Length-1) + " value " + this[Length-1]);
            return this[Length-1];
        }
    }

    public void WriteByte(byte value)
    {
        WriteIndex++;

        if (WriteIndex < Length)
        {
            Console.WriteLine("Wrote from index " + (WriteIndex-1) + " value " + value);
            this[WriteIndex - 1] = value;
        }

        else if(writeIndex == Length)
        {
            Console.WriteLine("Wrote from index " + (WriteIndex-1) + " value " + value);
            this[WriteIndex-1] = value;

            WriteIndex = 0;
        }
    }

    public byte this[int index]
    {
        get
        {
            lock(BufferLock)
            {
                return Buffer[index];
            }  
        }
        set
        {
            lock(BufferLock)
            {
                Buffer[index] = value;
            } 
        }
    }
}

第一个线程将使用方法ReadByte从此缓冲区获取字节,第二个线程将使用方法WriteByte将字节写入缓冲区。 我有writeindex和readindex正在缓冲区上移动。一切似乎都很好但是这个:

a bug http://i62.tinypic.com/2d9tmrd.png

任何想法/建议?希望你能帮助我,伙计们!

1 个答案:

答案 0 :(得分:-1)

希望我有足够的“声誉”来发表评论。无论如何,你为什么认为有问题?在你突出显示的红色框内,是不是等待的读者线程?一旦有机会运行它就选择了索引8,这是正确的值。