> in real life where do we use a circular queue
How about .... a wall clock? You got 60sec in a queue, second hand indicates current position in queue. Same for the 60 minutes, and minute hand.
> what are its computer implementations ?
The computer simulates the clock's queue through applied math. Ramifications: try handling that one where every so often they want you to add a second to the clock this year, but not last year or next.
Main Topics
Browse All Topics





by: _nn_Posted on 2003-08-25 at 03:52:56ID: 9215219
Every time you need a FIFO (First In First Out) buffer, it's smarter to use a circular buffer, because you avoid lengthy memory move operations :
Let's assume :
you've read "abcdefghij" from your COM port
[abcdefghij--------------]
now another thread wants to process the content byte per byte. You have to
* read one byte
[-bcdefghij--------------]
* move the entire buffer one byte to the left
[bcdefghij---------------]
That's slooooooooooooow and dumb.
Instead, use 2 pointers : one for reading, one for writing.
v
[abcdefghij--------------]
^
You never move the memory, you just update pointers (or array indexes). One must be careful with the implementation, i.e. :
- deal properly with overflows
- threads synchronization
but there are tons of freely available examples, just google a bit : "circular buffer queue" should get you tons of hits.
A real life example ? The kernel of our product is a console application. There are contexts threads associated with "lines" (this is a telephony application). Each of these lines has a debug output which is buffered in a FIFO, so that I can display at runtime the latest output of each of these "lines". Size of the buffers is limited. What algo did I use ? A circular buffer of course. In this case, they are a bit special though, since after a while, they are always full (oldest entries get overwritten by the newest ones). But it does the job I want : it tells me what are the latest events on each line.