There is 1 thread that writes to a file, and a number of other threads that can
ID: 3809904 • Letter: T
Question
There is 1 thread that writes to a file, and a number of other threads that can simultaneously read the file, but never the readers and the write together (e.g., at one time, 3 reader threads are running, at another time the writer thread is running). Write pseudo code using semaphores for both the Reader() and Writer() functions. Remember that there is no data dependency between the readers and the writer (i.e., it is not a producer-consumer problem), the only condition is that they do not happen at the same time. Hint: The first reader to get access waits until the ongoing writer (if any) finishes, performs the read operation and leaves. The last reader, just before leaving, should give control/access back to the writer (if any) waiting. Think about the initial values of the semaphores.
Explanation / Answer
Three variables will be used to implement the problem: mutex, wrt, readCount
1. Semaphore mutex is used to ensure mutual exclusion when readCount is updated.
2. Semaphore wrt is used by both readers and writers.
3. readCount will tell the number of processes performing read operation in the critical section, initially its value will be 0
Writer:
- It requests to enter in critical section.
- If request granted, i.e. wait() gives a true value, it enters and performs the write. If not granted, it keeps on waiting.
- It exits the critical section.
do {
// writer requests for critical section
wait(wrt);
// performs the write
<critical section>
// leaves the critical section
signal(wrt);
} while(true);
Reader:
do {
// reader requests for critical section
wait(mutex);
// number of readers will be increased by 1
readCount++;
// there is atleast one reader in the critical section, this ensure no writer can write if there is even one reader
if (readCount==1)
wait(wrt);
// other readers can enter this critical section while the current reader is inside or reading
signal(mutex);
// current reader performing reading operation
wait(mutex);
// a reader wants to leave
readCount--;
// that is, no reader is left in the critical section,
if (readCount == 0)
signal(wrt); // if all readers are done with reading operation then readCount will become 0 and writers can enter
signal(mutex); // reader leaves the process
} while(true);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.