Interview Questions

173. A program has two functions 'reader_func' and 'writer_func' .......

Microsoft Interview Questions and Answers


(Continued from previous question...)

173. A program has two functions 'reader_func' and 'writer_func' .......

Question:
A program has two functions 'reader_func' and 'writer_func'. The reader_func reads shared data and contains a critical section. The writer_func writes to shared data and contains a critical section.

Reader threads call reader_func. Writer threads call writer_func.
The condition is multiple reader threads can access the critical section at the same time as long as they don't access the critical section along with a writer. Only a single writer thread can access the critical section, i.e. no reader or other writer threads are allowed.

Give the code segment, add code that uses mutexes that controls access to the critical sections so that the shared data is not corrupted and satisfies the give conditions. You can create as many mutexes and global variables as you want. Don't emphasize too much on syntax as to how to acquire and release locks on mutexes. Just use mutex.acquire() and mutex.release() .

Code segment:
void reader_func()
{
//critical section
}

void writer_func()
{
//critical section
}




maybe an answer:


Mutex writerRequestMutex;
bool writerRequest=false;
int readerCount=0;
const int Max_Readers = 10;

void read_func()
{
writerRequestMutex.lock();
while(writerRequest!=false &&& readerCount>=Max_Readers)
{
writerRequestMutex.unlock();
doSleep();
writerRequestMutex.lock();
}

readerCount++;
writerRequestMutex.unlock();

//critical section

writerRequestMutex.lock();
readerCount--;
writerRequestMutex.unlock();

if(readerCount==0)
writerRequestMutex.wake();

}

void write_func()
{
writerRequestMutex.lock();
while(readerCount!=0)
{
writerRequest=true;
writerRequestMutex.wait();
}

//critical section

writerRequest=false;
writerRequestMutex.unlock();
}

(Continued on next question...)

Other Interview Questions