[Operating System] Reader - Writer Problem
A buffer is shared among several processes.
- Some are readers: they only want to read from the buffer.
- Some are writers: they want to make changes.
The goal is to prevent conflicts.
- At most one writer should have access at any given time.
- Readers and writers should not have access at the same time.
- However, it's okay for multiple readers to have access, because reads do not conflict with other reads.
Thought process:
We need to allow only readers or writers.
- Use a binary semaphore 'rw' that readers and writers take before accessing the buffer.
- But this would only allow one reader.
- We can let only the first reader take the semaphore.
How do we figure out who the first reader is?
- We can keep a counter of the number of active readers.
- We need another semaphore that readers take before updating the counter.
Solution:
1 2 3 4 | volatile Buffer buffer; volatile count = 0; Semaphore rw = new Semaphore(1); Semaphore mutex = new Semaphore(1); |
1 2 3 4 5 6 7 | void writer() { while (true) { rw.P(); buffer.write(); rw.V(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | void reader() { while (true) { mutex.P(); count++; if (count == 1) { rw.P(); } mutex.V(); buffer.read(); mutex.P(); count--; if (count == 0) { rw.V(); } mutex.V(); } } |
Comments
Post a Comment