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. ...
-
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...
-
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...
-
Pyglet 1.1 comes with a shiny new event loop. I've always liked to control my own mainloop, so that I can implement things like fixed t...
-
Often, when building a game, you need to test if objects are colliding. The objects could be spaceships, rocks, mouse pointers, laser beams....
-
MiddleMan: A Pub/Sub and Request/Response server in Go. This is my first Go project. It is a rewrite of an existing Python server, based o...
-
I went to the pulse expo this evening, where one of the speakers mentioned that Ubisoft are in town (Perth, Western Australia), looking to...
-
I've built sites with Django, TurboGears and Pylons. I've come to prefer Pylons. Why? Pylons gets out of the way, and stays out of t...
-
iPhone developers... weep. The new terms of service for iPhone OS 4.0 has an awful restriciton. 3.3.1 Applications may only use Documented A...
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