Code reviewThe bounded queue

time to read 1 min | 64 words

The following code has just been written (never run, never tested).

public class SingleProducerSingleConsumerCircularQueue
{
const int QueueSize = 256;
volatile int _readPos, _writePos;
private readonly byte[][] _data = new byte[QueueSize][];
int PositionToArrayIndex(int pos)
{
return pos % QueueSize;
}
public bool Enqueue(byte[] entry)
{
int readIndex = PositionToArrayIndex(_readPos);
int writeIndex = PositionToArrayIndex(_writePos+1);
if (readIndex == writeIndex)
return false; // queue full
_data[PositionToArrayIndex(_writePos)] = entry;
_writePos++;
return true;
}
public bool Dequeue(out byte[] entry)
{
entry = null;
int readIndex = PositionToArrayIndex(_readPos);
int writeIndex = PositionToArrayIndex(_writePos);
if (readIndex == writeIndex)
return false;// queue empty
entry = _data[readIndex];
_data[_readPos] = null;
_readPos++;
return true;
}
}

It’s purpose is to serve as a high speed, no locking transport between two threads, once of them producing information, the other consuming it, in a bounded, non blocking manner.

Note that this is done because the default usage of BlockingCollection<T> here generated roughly 80% of the load, which is not ideal

More posts in "Code review" series:

  1. (26 Jun 2016) The bounded queue
  2. (15 Apr 2011) Who Can Help Me
  3. (01 Apr 2011) SharpArchitecture.MultiTenant
  4. (28 Nov 2007) PetShop 3.0
  5. (28 Nov 2007) The PetShop Application