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?
Submitted by: AdministratorHow 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;
}
Submitted by: Administrator
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;
}
Submitted by: Administrator
Read Online Apple Job Interview Questions And Answers
Top Apple Questions
☺ | Explain popular apps of iPhone? |
☺ | Explain iphone architecture? |
☺ | How to parse a phone number from a huge database of a n billion webpages in 30 minutes |
☺ | Design a chess game. Basics of a chess game was explained and a player could be human or AI? |
☺ | Please explain the difference between shallow copy and deep copy? |
Top Companies Job Categories
☺ | TCS Interview Questions. |
☺ | Infosys Interview Questions. |
☺ | IBM Interview Questions. |
☺ | Wipro Interview Questions. |
☺ | Google Interview Questions. |