Implement a thread safe FIFO queue
/**
Implement a synchronized fifo queue - storage and two operations (read/write)
Read: Block until a value can be returned. (Optional Timeout). FIFO semantics. Remove first element and return it.
Write: If queue is full, wait (timeout). FIFO wait for other writers. Write element.
Reads and Writes should be able to happen in parallel.*/
public class Queue<T>
{
private int start = 0;
private int end = 0;
private int capacity = 0;
private Lock writeLock;
private T[] buffer;
private Queue(int capacity)
{
// check capacity for invalid case like negative value...
this.capacity = capacity;
buffer = new T[capacity];
}
// read
public T Dequeue()
{
while (start >= end)
{
}
lock (writeLock)
{
return this.buffer[start++];
}
}
// write
public bool Enqueue(T item)
{
while (end - start >= this.capacity)
{
}
lock (writeLock)
{
if (end >= this.capacity)
{
for (int i = 0; i <= end - start; i++)
{
this.buffer[i] = this.buffer[i + start];
}
end = end - start;
start = 0;
}
this.buffer[end++] = item;
return true;
}
}
// test case 1. : capacity = 3 E(1) E(2) E(3) E(4)
// E(1) -> [1] start = 0, end = 1
// E(2) -> [1, 2] start = 0, end = 2
// E(3) -> [1, 2, 3] start = 0, end = 3
// E(4) -> [1, 2, 3] start = 0, end = 3 return false;
// test case 2. : capacity = 3 E(1) E(2) E(3) D() E(4)
// E(1) -> [1] start = 0, end = 1
// E(2) -> [1, 2] start = 0, end = 2
// E(3) -> [1, 2, 3] start = 0, end = 3
// D() -> return 1, start = 1, end = 3
// E(4) -> [1, 2, 3] start = 1, end = 3 [2, 3, 4]
}