Monday, October 25, 2010

Generic Thread Safe RingQueue in C#

using System;
using System.Threading;



public class RingQueue
{
private int size;
private int read = 0;
private int write = 0;
private int count = 0;
private T[] objects;
private AutoResetEvent addEvent;
private AutoResetEvent popEvent;

public RingQueue (int size)
{
addEvent = new AutoResetEvent (false);
popEvent = new AutoResetEvent (false);
this.size = size;
objects = new T[size + 1];
}

public bool Empty {
get {
lock (this) {
return (read == write) && (count == 0);
}
}
}

public bool Full {
get {
lock (this) {
return (read == write) && (count > 0);
}
}
}

public void Add (T item)
{
lock (popEvent) {
if (Full) {
popEvent.WaitOne ();
}
objects[write] = item;
count++;
write = (write + 1) % size;
addEvent.Set ();
}

}

public T Pop ()
{
lock (addEvent) {
if (Empty) {
addEvent.WaitOne ();
}
T item = objects[read];
count--;
read = (read + 1) % size;
popEvent.Set ();
return item;
}
}
}

No comments:

Popular Posts