gby
gby

Reputation: 15218

Can only read one element at once of a circular buffer

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.

Upvotes: 1

Views: 420

Answers (1)

Kurru
Kurru

Reputation: 14331

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

Upvotes: 1

Related Questions