public class RingQueue<T>
{
private int size;
private int read = 0;
private int write = 0;
private int count = 0;
private T[] objects;
public RingQueue (int size)
{
this.size = size;
objects = new T[size + 1];
}
public bool Empty {
get { return (read == write) && (count == 0); }
}
public bool Full {
get { return (read == write) && (count > 0); }
}
public void Write (T item)
{
if (Full)
throw new IndexOutOfRangeException ("Queue Full!");
objects[write] = item;
count++;
write = (write + 1) % size;
}
public T Read ()
{
if (Empty)
throw new IndexOutOfRangeException ("Queue Empty!");
T item = objects[read];
count--;
read = (read + 1) % size;
return item;
}
}
Monday, July 12, 2010
Generic Ring Buffer in C#
This data structure is helpful when creating lock-free algorithms. I'm not sure if the exceptions used are appropriate. Any suggestions?
Subscribe to:
Post Comments (Atom)
Popular Posts
-
These are the robots I've been working on for the last 12 months. They each weigh about 11 tonnes and have a 17 meter reach. The control...
-
So, you've created a car prefab using WheelCollider components, and now you can apply a motorTorque to make the whole thing move along. ...
-
The procedural planet package has been updated to version 1.4, and you can see the new demo here . It features better city light control, be...
-
I have just spent an hour trying to track down a weird bug in some Javascript interpolation code. The offending code looks like this: var n ...
-
Why would I ask that question? Python 3 has been available for some time now, yet uptake is slow. There aren't a whole lot of packages i...
-
I've just finished refactoring an awful C# class. I had been delaying the job for a while because I didn't want to do it. Then, whil...
-
Dear Lazyweb. Imagine a nice RESTful interface for working with Tags. The URL: /tags/ will return a list of all the tags. The URL: /tags/fo...
-
Summary: NodeJS wins. Test Program ab -n 10000 -c 5 http://localhost/ Gevent Code from gevent import wsgi class WebServer(object): def a...
-
After my last post, I decided to benchmark the scaling properties of Stackless, Kamaelia, Fibra using the same hackysack algorithm. Left axi...
-
I've just uploaded Fibra 2 to the cheeseshop. Fibra 2 includes the promised non-blocking plugin, which allows a generator based task to...
1 comment:
When writing, perhaps instead of an exception, you could grow the queue. Allocate a new array, copy the existing elements and then add the new item.
For reading, it seems appropriate to me, given the Empty property - there is a test to avoid the exception.
The other alternative is to return null, and let the application handle it. If not handled, a NullReferenceException would eventually result. Hmm.
Post a Comment