Sergio wrote: > Ok, further to Dave's asertion that we could use a flag to allow us to > completely fill the FIFO. I have revised the FIFO code I posted and come > up with the following (appended to the end of this post). It uses two > extra counts instead of the one flag proposed by Dave. Actually, that gives me an idea. If you simply allow the "head" and "tail" variables to count to twice the size of the FIFO, then they can perform both the indexing function and the counting function, with very little additional overhead, and no added thread-safety issues. If FIFO_SIZE is a power of two, then all of the '%' (modulus) operators can become '&' (bitwise AND) operators, efficient even on tiny processors. -- Dave Tweed ======================================================== #define FIFO_SIZE 100 typedef struct { unsigned int head; unsigned int tail; int data[FIFO_SIZE]; } FIFO; void fifo_init (FIFO *f) { f->head = 0; f->tail = 0; } unsigned int fifo_count (FIFO *f) { int count = f->head - f->tail; return count < 0 ? count + FIFO_SIZE*2 : count; } void fifo_add (FIFO *f, int item) { if (fifo_count (f) >= FIFO_SIZE) { /* TBD: It's an error if the FIFO is already full, * or you can wait here for an item to be removed. */ } f->data[f->head % FIFO_SIZE] = item; f->head = (f->head + 1) % FIFO_SIZE*2; } int fifo_remove (FIFO *f) { int item; if (f->head == f->tail) { /* TBD: It's an error if the FIFO is already empty, * or you can wait here for an item to be added. */ } item = f->data[f->tail % FIFO_SIZE]; f->tail = (f->tail + 1) % FIFO_SIZE*2; return item; } ======================================================== -- http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist