views:

34

answers:

1

I have implemented the standard single consumer, single producer queue as a circular buffer in C consisting of an array and two indexes: one for read, one for write.

My circular buffer is of the type that returns an error if you attempt to insert an item into a full queue and uses one empty slot to distinguish between an empty ring buffer and a full one.

While debugging it I noticed it sometime slipped into a consistent state where you could only read a single item at a time before getting the return value that meant the buffer is full, even though there was an ongoing thread that does inserts all the time.

I assumed I must have done something silly in implementation but could not find anything. I then decided to double check the logic and re-read the Wikipedia value that describes such queues.

Much to my surprise, I noticed the following cryptic comment in the text:

If you cannot read over the buffer border, you get a lot of situations where you can only read one element at once.

So, if I understand the meaning correctly, this seems to indicate that this is some sort inherit problem with this way of implementing such a ring buffer.

Alas, my feeble brain is at a lose to understand the root cause of this problem: why is this happening? what sequence of inserts and erases can get such a ring buffer into this state?

You help is greatly appreciated.

A: 

Umm, I presume you're being carefull to syncronize the functions so you don't get concurrency issues? Not doing that can cause bad buffer behaviour randomly

Kurru
Yes Jurru, I am. The insert and delete are protected with a spin lock. It is the same lock for the insert and delete and it is taken at the begining of each operation. And yes, there ways to make it more efficient (different lock for read and write for example), I just want to get it working first :-)As far as I can tell there is no locking protocol error and the input/output from the queue is correct it is just interlocked.In fact, I am thinking that the locking is causing this interlocking, I just can't seem to explain how.Thanks,Gilad
gby
If you're relying on your own implementation of a spinlock, there could be race-conditions in your lock. if you're not using an atomic set-and-test operation. But i'm no C expert.
Kurru