473,669 Members | 2,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Circular Buffer Question

Working with implementing a circular buffer for a producer/consumer deal.
Have not done one in a while. The following seems to work. However, I
remember and have seen other implementation that make the buffer 1 more then
the needed capacity so that a full buffer and an empty buffer can be
differentiated. However this implementation does not do that (i.e. the
capacity and the buffer size is the same.) I assume the following does not
need the extra buffer element because I am always tracking "used" (where the
other implementation would not do that as you could calculate that with the
readPos/writePos markers.) Just wondering if this imp. will somehow break
down for certain things or what the pros or cons are between the two
implementations (this seems a bit more straight forward)? TIA

//no locking yet.
public class CircularBuffer
{
private object[] buffer;
public int readPos;
public int writePos;
public int used;
public int size;

public CircularBuffer( int size)
{
this.size = size;
buffer = new object[size];
readPos = 0;
writePos = 0;
used = 0;
}
public void Put(object o)
{
if (IsFull())
throw new ApplicationExce ption("Buffer is Full.");
buffer[writePos] = o;
writePos = (writePos + 1) % size;
used++;
}
public object Get()
{
if (IsEmpty())
throw new ApplicationExce ption("Buffer is Empty.");
object o = buffer[readPos];
readPos = (readPos + 1) % size;
used--;
return o;
}
public bool IsFull()
{
return (used == size);
}
public bool IsEmpty()
{
return (used == 0);
}
public int Free
{
get { return size - used; }
}
} // End Class

--
William Stacey

Nov 15 '05 #1
2 6618

Hi William,

I think it is the same with the circular queue in data structure.
There is 2 ways of implement the circular queue:
1. Use tail, head pointer and empty flag.
initial value: tail=head=0
empty mode: tail=head and empty=true;
full mode: tail=head and empty=false;

2. Give up the empty flag, but you must let one momery cell
not use.
Initial value: tail=head=0
empty mode: tail=head
full mode: (tail+1)%SIZE=h ead

For you sample code, it is the same with the first implement, but
it changes empty flag for used flag.

For multi-threading application, you should be careful of the share
variables: tail, head, empty.
You should use some mutex mechanism to protect them.

Hope this helps,
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
| From: "William Stacey" <st*****@mvps.o rg>
| Subject: Circular Buffer Question
| Date: Mon, 29 Sep 2003 11:26:40 -0400
| Lines: 65
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.3790.0
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| Message-ID: <eR************ **@TK2MSFTNGP10 .phx.gbl>
| Newsgroups: microsoft.publi c.dotnet.langua ges.csharp
| NNTP-Posting-Host: 66.188.59.114.b ay.mi.chartermi .net 66.188.59.114
| Path: cpmsftngxa06.ph x.gbl!TK2MSFTNG P08.phx.gbl!TK2 MSFTNGP10.phx.g bl
| Xref: cpmsftngxa06.ph x.gbl microsoft.publi c.dotnet.langua ges.csharp:1880 05
| X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.csharp
|
| Working with implementing a circular buffer for a producer/consumer deal.
| Have not done one in a while. The following seems to work. However, I
| remember and have seen other implementation that make the buffer 1 more
then
| the needed capacity so that a full buffer and an empty buffer can be
| differentiated. However this implementation does not do that (i.e. the
| capacity and the buffer size is the same.) I assume the following does
not
| need the extra buffer element because I am always tracking "used" (where
the
| other implementation would not do that as you could calculate that with
the
| readPos/writePos markers.) Just wondering if this imp. will somehow break
| down for certain things or what the pros or cons are between the two
| implementations (this seems a bit more straight forward)? TIA
|
| //no locking yet.
| public class CircularBuffer
| {
| private object[] buffer;
| public int readPos;
| public int writePos;
| public int used;
| public int size;
|
| public CircularBuffer( int size)
| {
| this.size = size;
| buffer = new object[size];
| readPos = 0;
| writePos = 0;
| used = 0;
| }
| public void Put(object o)
| {
| if (IsFull())
| throw new ApplicationExce ption("Buffer is Full.");
| buffer[writePos] = o;
| writePos = (writePos + 1) % size;
| used++;
| }
| public object Get()
| {
| if (IsEmpty())
| throw new ApplicationExce ption("Buffer is Empty.");
| object o = buffer[readPos];
| readPos = (readPos + 1) % size;
| used--;
| return o;
| }
| public bool IsFull()
| {
| return (used == size);
| }
| public bool IsEmpty()
| {
| return (used == 0);
| }
| public int Free
| {
| get { return size - used; }
| }
| } // End Class
|
| --
| William Stacey
|
|
|
|

Nov 15 '05 #2
> For multi-threading application, you should be careful of the share
variables: tail, head, empty.
You should use some mutex mechanism to protect them.


Thank you Jeffery. I did run into this issue in a marathon debug session
today. Although I was locking the puts and gets and the other vars, I ran
into one of those strange sync issues that don't happen every time you run
it. When I put the last buffer in the cBuffer, that worked fine. However,
from the producer code, you can't tell it that this is the last byte[] until
after the Put() (I guess ya could if you put another sync wrapper) I set an
"InputCompl ete" flag in the cbuffer class right after the last "Put". Well,
luck has it that every once in a while a thread switch happens right after
the consumer tests for Empty and waits on a pulse from producer and did not
pick up the fact that the producer set the "InputCompl ete" flag. Short
story is I worked this out by sending a null in the stream to indicate a
stream done condition which simplifies the logic a bit. Many things to
watch out for to sync data structures. Anyway, a hard one to find and
diagnose - thanks for the help!

--
William Stacey, DNS MVP

Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1788
by: andy.dreistadt | last post by:
Hi all, I came across another problem that is probably pretty easy but, again, due to my rusty-ness with C, I'm a little stumped. I have a struct that looks like this: /* Instrument Data structure */ struct instrument_info {
9
1724
by: sunway | last post by:
i have written a small program, it turns out to be wrong, while(read()!=EOF){ read(); read(); read(); } so,when read==EOF,the next read() will read a -1, and the program will go infinitely.
7
20005
by: toton | last post by:
Hi, I want a circular buffer or queue like container (queue with array implementation). Moreover I want random access over the elements. And addition at tail and remove from head need to be low cost. STL vector is suitable for removing form tail? or it is as costly as removing from middle? any other std container to serve this purpose? (note , I dont need linked list implementation of any container, as I want random access)
2
7760
by: marco.furlan | last post by:
Hi there, I have to write an optimized circular buffer to log events in C++. The elements are of type std::string. This should run under Linux on an ARM embedded system. I can dedicate to this circular log a preallocated block of fixed size and work in there. Can anybody indicate me an example or technique to do this ? Thanks Marco
9
2684
by: thiago777 | last post by:
I have four methods(threads) in my application that must work syncronized sharing an 8 element circular buffer array. Each method should work in the data only after its previous thread had completed its task, in the following order: 1st.: Reads data from file and place in one free element of the array; 2nd.:Read data produced by thread 1, change and save; 3rd.: Read data produced by thread 2, change and save; 4th.: Get processed data from...
2
2539
by: sharanap | last post by:
Implement a circular buffer of size 32 using an array inC, can anybody tel the answer, this que. asked to my friends in an interview
12
7123
by: Sven | last post by:
Can someone point out source code for a safe circular buffer receiver transmitter? It's for sending and receiving bytes via RS232. Thanks in advance.
1
6423
by: codedinC | last post by:
Is there a way to test to see if stdin is empty, or to see if there is data that has not been read from the buffer.
0
8894
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8803
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8587
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6210
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2029
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1787
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.