A simple character FIFO I wrote for my Rocket project.
Revision 0:093546398fcd, committed 2017-06-11
- Comitter:
- danjulio
- Date:
- Sun Jun 11 04:06:39 2017 +0000
- Commit message:
- Initial commit
Changed in this revision
StringFifo.cpp | Show annotated file Show diff for this revision Revisions of this file |
StringFifo.h | Show annotated file Show diff for this revision Revisions of this file |
diff -r 000000000000 -r 093546398fcd StringFifo.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StringFifo.cpp Sun Jun 11 04:06:39 2017 +0000 @@ -0,0 +1,78 @@ +/* + * StringFifo: A simple FIFO class for passing strings between threads. + */ +#include "StringFifo.h" + +StringFifo::StringFifo(int size) +{ + sP = (char *) malloc(size); + if (sP != NULL) { + len = size; + } else { + len = 0; + } + pushI = 0; + popI = 0; +} + +StringFifo::~StringFifo() +{ + free(sP); + len = 0; +} + +void StringFifo::PushString(char* s) +{ + int sLen; + int i; + + push_mutex.lock(); + + // Compute the required room + sLen = 0; + while (*(s+sLen) != 0) sLen++; + sLen += 1; // Add in null character + + // Wait until there is room + while (Remaining() < sLen) { + Thread::yield(); + } + + // Push the string + i = pushI; + while ((*(sP + i) = *s++) != 0) { + i = (i + 1) % len; + } + + // Atomically update pushI + pushI = (i + 1) % len; // Always point to next location to fill + + push_mutex.unlock(); +} + +void StringFifo::PopString(char* s) +{ + int i; + + // Wait until there is a string to pop + while (IsEmpty()) { + Thread::yield(); + } + + // Get the string + i = popI; + while ((*s++ = *(sP + i)) != 0) { + i = (i + 1) % len; + } + + // Update popI + popI = (i + 1) % len; // Always point to start of next string +} + +int StringFifo::Remaining() +{ + if (pushI >= popI) + return (len - pushI + popI); + else + return (popI - pushI); +}
diff -r 000000000000 -r 093546398fcd StringFifo.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StringFifo.h Sun Jun 11 04:06:39 2017 +0000 @@ -0,0 +1,37 @@ +/* + * StringFifo: A simple FIFO class for passing strings between threads. + * Includes a mutex on the load end to allow different threads to + * push strings. Strings are delimited by null characters, both as they + * are pushed into the FIFO and as they are stored internally. Execution + * yields for a pushing thread if there is not room or if another thread + * is currently pushing data. Execution blocks for a reading thread until + * there is data to read. + * + */ +#ifndef STRING_FIFO_H +#define STRING_FIFO_H + +#include "mbed.h" + +class StringFifo { + public: + StringFifo(int size = 1024); + ~StringFifo(); + + void PushString(char* s); + inline bool IsEmpty() {return pushI == popI;} + void PopString(char* s); + + private: + // Methods + int Remaining(); + + // Variables + char* sP; + int len; + int pushI; + int popI; + Mutex push_mutex; +}; + +#endif \ No newline at end of file