//mutexless circular buffer //this design is pretty well tested but is meant as an example //feel free to use it as you see fit but don't blame me when //you lunar lander crashes into the sun. //author: christopher pepe //date: 19 June 2007 #include #include #include "fifo.h" //example usage of the circular fifo written in C //This queue design allows mutexless protection of data that is used by multiple sources by // seperating the read and write operations and only allowing reads of fully written data. int main() { fifo* demoFifo; int x, y, cnt, check; uint16_t putBuf[1024]; uint16_t getBuf[1024]; int showLast = 1; //make the queue with 8 items each with 1024 slots of 2 bytes each demoFifo = FifoInit(demoFifo,8,1024, 2); //fill queue with nonsense data for(x=0; x<15;x++) { //fill a buffer for(y=0;y<1024;y++) { //x is the slot the buffer gets put in the queue //this makes it easy to verify that the correct data //is read back later. putBuf[y] = x; } //copy that buffer to the queue check = FifoPut(demoFifo, (unsigned int*)putBuf); if( check == NOSPACE ) { printf("No free space, discarding %d's\n", x); } if( x % 2 == 0 ) { check = FifoGet(demoFifo, (unsigned int*)getBuf); if( check != SOFTERROR ) { //getBuf now contains the contents of the head of //the queue. Here's a little proof. This is a single //value from the buffer - see below to output the entire //buffer. printf("[epoch %d] Got Data from fifo: value = %d", x, getBuf[x]); if(check == WRAP) { if(debug)printf("\t<--wrapped around\n"); if(!debug)printf("\n"); } else { printf("\n"); } } } } /* //read back some of the nonsense for(x=0;x<4;x++) { //make sure we actually read back the buffer check = FifoGet(demoFifo, (unsigned int*)getBuf); if( check != SOFTERROR ) { //getBuf now contains the contents of the head of //the queue. Here's a little proof. printf("getBuf %d value = %d", x, getBuf[x]); if(check == WRAP) { printf("\t<--wrapped around\n"); } else { printf("\n"); } } } */ //set showLast to 1 to dump the contents of the last //buffer that gets pulled from the fifo if(showLast) { printf("\nContents of buffer:\n"); for(x=0;x<32;x++) { for(y=0;y<32;y++) { printf("%d ", getBuf[x*32+y]); } printf("\n"); } } //the read and write count. Notice that even though //there are only 8 slots these counts continue on. This //queue relys on the difference in the counts so their //actual values don't really matter so long as they are //unsigned (for when they wrap) printf("read: %d\n", demoFifo->read); printf("write: %d\n", demoFifo->written); return 0; }