
1
page 1
CS 361 Concurrent programming
Drexel University
Fall 2004
Lecture 14
©Bruce Char and Vera Zaychik. All rights reserved by the author.
Permission is given to students enrolled in CS361 Fall 2004to
reproduce these notes for their own use.
page 2
Database reader/writer problem
• The readers and writers problem: readers may read a
database simultaneously as long as no writer writes
• Only one writer at a time may write (if there are no active
readers).
• Attain: maximal parallelism (readers may read
simultaneously if there is no writing), data integrity (only
one writer at a time if no readers are reading).
• Possible additional goal: avoid writer starvation (locked
out of writing because readers are always coming along to
read).
page 3
Database reader/writer solution
import Utilities.*;
import Synchronization.*;
class Database extends MyObject {
private int numReaders = 0;
private BinarySemaphore mutex = new B inarySemaphore(1);
private BinarySemaphore ok = new Bina rySemaphore(1);
public Database() { super("Database") ; }
page 4
Reader code
public void startRead(int i) {
P(mutex);
numReaders++;
if (numReaders == 1) {
System.out.println("age=" + age() + " reader " + i
+ " waiting to read, numReaders=" + numReaders);
P(ok);
}
System.out.println(" age=" + age() + " reader " + i
+ " has begun reading, numReaders=" + numReaders);
V(mutex);
}
public void endRead(int i) {
P(mutex);
numReaders--;
System.out.println(" age=" + age() + " reader " + i
+ " finished reading, numReaders=" + numReaders);
if (numReaders == 0) V(ok);
V(mutex);
}
page 5
Writer code
public void startWrite(int i) {
P(ok);
System.out.println(" age=" + age() + " WRITER " + i
+ " has begun Writing");
}
public void endWrite(int i) {
System.out.println(" age=" + age() + " WRITER " + i
+ " has finished Writing");
V(ok);
}
}
page 6
Notes on reader/writer solution
– Only the first reader should lock the “ok” lock.
The last reader should unlock it when it finishes
its read. Then the
– Writers can write. Starvation of writers might
occur.