Apple Question:
Download Job Interview Questions and Answers PDF
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;
}
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;
}
Download Apple Interview Questions And Answers
PDF