I developed a solution for the reader/writer problem in java (some information on this http://lass.cs.umass.edu/~shenoy/courses/fall08/lectures/Lec11.pdf ).
However I am not sure how to modify the code to either favor writers or give both reader and writer same priority. What type of this problem is my code and how do I see it?
public class ReaderWriter{
int numberOfReaders;
int numberOfWriters;
public ReaderWriter(){
this.numberOfReaders = 0;
this.numberOfWriters = 0;
}
public synchronized void requestRead(){
while(this.numberOfWriters > 0)
wait();
this.numberOfReaders++;
}
public synchronized void releaseRead(){
this.numberOfReaders--;
notifyAll();
}
public synchronized void requestWrite(){
while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
wait();
this.numberOfWriters++;
}
public synchronized void releaseWrite(){
this.numberOfWriters--;
notifyAll();
}
}
Your version favors readers (and can starve writers). Here is a modified version that favors writers (and can starve readers):
int numberOfReaders;
int numberOfWriters;
int numberOfRequestedWriters; // ++
public ReaderWriter(){
this.numberOfReaders = 0;
this.numberOfWriters = 0;
this.numberOfRequestedWriters = 0; // ++
}
public synchronized void requestRead(){
while(this.numberOfWriters > 0 // --
|| this.numberOfRequestedWriters > 0) // ++
wait();
this.numberOfReaders++;
}
public synchronized void releaseRead(){
this.numberOfReaders--;
notifyAll();
}
public synchronized void requestWrite(){
this.numberOfRequestedWriters++; // ++
while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
wait();
this.numberOfRequestedWriters--; // ++
this.numberOfWriters++;
}
public synchronized void releaseWrite(){
this.numberOfWriters--;
notifyAll();
}
}
To control how locks are distributed, you need to maintain a queue of waiting threads. Unless the section of code you are protecting is expensive, a simple lock may be better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.