Microsoft Interview Question
Software Engineer / DevelopersTeam: Azure
Country: United States
Interview Type: In-Person
tested implementation of it. it takes int instead of byte array. its for C++ 11
#include "stdafx.h"
#include<iostream>
#include<thread>
#include<mutex>
#define defaultSize 50
using namespace std;
class CircullarArray{
private:
int *myQueue;
int top;
int tail;
int max;
mutex myMutex;
public:
void init(int size){
if (size < 0)
size = defaultSize;
myQueue = new int[size];
top = -1;
tail = -1;
max = size;
}
bool isFull(){
return ((tail == 0 && top == max - 1) || (tail == top + 1)) ? 1 : 0;
}
bool isEmpty(){
return (tail == -1) ? 1 : 0;
}
void push(int value){
myMutex.lock();
if (isFull())
cout << "Queue is Full!" << endl;
else{
top = (top + 1) % max;
myQueue[top] = value;
}
if (tail == -1)
tail = 0;
myMutex.unlock();
}
void pop(){
myMutex.lock();
int data;
if (isEmpty()){
cout<<"Queus is empty"<<endl;
myMutex.unlock();
return;
}
data = myQueue[tail];
if (tail == top){
top = -1;
tail = -1;
}
else
tail = (tail + 1) % max;
cout << data << endl;
myMutex.unlock();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CircullarArray *circullarArray = new CircullarArray();
// do staff here
thread thread1(&CircullarArray::pop, circullarArray);
thread thread2(&CircullarArray::pop, circullarArray);
// wait untill the threads finish their task in case the main thread finish early.
thread1.join();
thread2.join();
}
Code of Queue itself and tester (we basically allow only one read and only one write, but read and write can be at the same time). I'd also ask if interviewer wants to implement producer/consumer model - means, read will wait until queue has needed count of bytes and write will wait until needed bytes will be freed. Code below doesn't implement producer/consumer though.
- AK October 29, 2014