Click to See Complete Forum and Search --> : Circular Buffer


montana322
March 11th, 2008, 12:37 PM
Could someone show me how to write a circular buffer in C.
Basically my program will have multiple threads and all have to use the same buffer, some threads write to it others read, and others modify.

The syncronization is not too hard, i just cant find a circular buffer example anywhere, to see how it works.

treuss
March 11th, 2008, 01:25 PM
You could use a std::deque, push items into it and pop them from the other end. Admitted, that's a FIFO not a circular buffer.

Plasmator
March 11th, 2008, 01:31 PM
Admitted, that's a FIFO not a circular buffer.And also C++. :wave:

treuss
March 11th, 2008, 01:54 PM
And also C++. :wave:Well, it's a C++ forum, isn't it ? ;)

Plasmator
March 11th, 2008, 01:57 PM
Well, it's a C++ forum, isn't it ? ;)Both C and C++, actually. :p It's just that the majority of the questions/responses here are related to C++.
Ask or answer C and C++ questions not related to Visual C++. This includes Console programming, Linux programming, or general ANSI C++.

OP: treuss' concept is still valid and of course transferable to C. I'm pretty sure that you didn't google well enough, though. =)

Lindley
March 11th, 2008, 02:04 PM
Is a circular linked list good enough? That shouldn't be too hard to do.

laserlight
March 11th, 2008, 02:05 PM
treuss' concept is still valid and of course transferable to C.
hmm... but a std::deque is more complicated than a circular buffer, methinks.

jefranki
March 11th, 2008, 02:05 PM
A circular buffer is essentially just an array that when you get to the end of the array, you start writing at the beginning again. You'll need something to keep track of your current position, the length of the array, and something to keep track of the last read position (to prevent overwrite, if neccessary).

I'll leave the implementation up to you, as this sounds a bit like a homework problem.

montana322
March 11th, 2008, 03:02 PM
Wow so i guess when someone posts for the first time, automatically its assumed its a homework assignment lol. what a nice welcome.

Well i knew it can be implemented as an array i was asking for any examples, but whatever, ill write from scratch.

For those who want to know
the assignment is actually a conversation program that uses multiple threads for input, conversion and output. The amount of threads for each phase is specified at runtime, and only one data structure can be used, so basically tests if you can use process synchronization