| 1. |
The Producers Write Elements To A Ring Buffer(fixed Size) While The Consumers Access Elements From It. Implement A Write And A Read Function Using A Producer Pointer And Consumer Pointer. The Consumer Pointer Cannot Surpass The Producer Pointer And When The Producer Pointer Reaches Where It Starts Again, It Stops? |
|
Answer» How about this? For multithreading, put MUTEX in write TEMPLATE<typename T> class writeandread { public: writeandread(T* s, int n):start(s), writePtr(s),readPtr(s), maxbytes(n), numofeles(0) {} T* getStartPtr(){return start;} T* getwritePtr(){return writePtr;} T* getreadPtr(){return readPtr;} bool write(T* INPUT, int n); T* read(int n); private: T* start, *writePtr, *readPtr; size_t maxbytes, numofeles; }; template<typename T> bool writeandread<T>::write(T* input, int n) { if (input == NULL && n > 0) return FALSE; if (maxbytes-numofeles < n*SIZEOF(T)/sizeof(char)) return false; numofeles += n*sizeof(T)/sizeof(char); for (int i = 0; i < n; ++i) { *writePtr = *input; ++writePtr; ++input; } return true; } template<typename T> T* writeandread<T>::read(int n) { if (n <= 0) return NULL; T* res = (T*) malloc(n); T* t = res; int count = 0; while (writePtr != readPtr) { *t = *readPtr; ++t; readPtr += sizeof(T); ++count; } if (count < n) readPtr = start; return res; } How about this? For multithreading, put mutex in write template<typename T> class writeandread { public: writeandread(T* s, int n):start(s), writePtr(s),readPtr(s), maxbytes(n), numofeles(0) {} T* getStartPtr(){return start;} T* getwritePtr(){return writePtr;} T* getreadPtr(){return readPtr;} bool write(T* input, int n); T* read(int n); private: T* start, *writePtr, *readPtr; size_t maxbytes, numofeles; }; template<typename T> bool writeandread<T>::write(T* input, int n) { if (input == NULL && n > 0) return false; if (maxbytes-numofeles < n*sizeof(T)/sizeof(char)) return false; numofeles += n*sizeof(T)/sizeof(char); for (int i = 0; i < n; ++i) { *writePtr = *input; ++writePtr; ++input; } return true; } template<typename T> T* writeandread<T>::read(int n) { if (n <= 0) return NULL; T* res = (T*) malloc(n); T* t = res; int count = 0; while (writePtr != readPtr) { *t = *readPtr; ++t; readPtr += sizeof(T); ++count; } if (count < n) readPtr = start; return res; } |
|