// 读者写者问题
using system;
using system.threading;
public class book{
private int[] pages;
private bool awriterwait = false;
private int readercount = 0;
private object mutex = new object(); // 控制对 readercount 的访问
private object db = new object(); // 控制对 pages 的访问
private object obj = new object(); // 控制对 awriterwait 的访问
public book(int numofpages){
pages = new int[numofpages];
}
public int numofpages{
get{
return pages.length; //常量,无须同步
}
}
public int this[int index]{
get{
lock(obj){
while( awriterwait ){
monitor.wait(obj);
}
}
lock(mutex){
// readercount的锁
// 检查是否为第一个读者
readercount++;
if(readercount == 1) monitor.enter(db);
}
int valuecopy = pages[index]; // 读取一个数据
console.writeline( thread.currentthread.name + " 读了 第" + (index + 1) + "页,他读到的数据是" + valuecopy );
displaycontent();
lock(mutex){
readercount--;
if(readercount == 0) monitor.exit(db);
}
return valuecopy;
}
set{
lock (obj){
awriterwait = true;
}
lock(db){ // 阻止其他的写者去写书
pages[index] = value;
console.writeline( thread.currentthread.name + "把" + value + "写到第" + (index + 1) + "页");
displaycontent();
}
lock(obj){
awriterwait = false;
monitor.pulseall(obj); // 通知等待的读者
}
}
}
private void displaycontent(){
console.writeline("{0,-35}","书的内容是:");
for(int i = 0;i < pages.length;i++){
console.write("{0,-9}",pages[i]);
}
console.writeline("\r\n");
}
}
public class reader{
private book book;
private random rand;
public reader(book b,random random){
book = b;
rand = random;
}
public void read(){
for (int i=0; i < 5; i++){
int p = rand.next(0,book.numofpages);
int a = book[p];
thread.sleep(rand.next(0,100));
}
}
}
public class writer{
private book book;
private random rand;
public writer(book b,random random){
book = b;
rand = random;
}
public void write(){
for(int i = 0;i < 5;i++){
int p = rand.next(0,book.numofpages);
book[p] = rand.next(50,100);
thread.sleep(rand.next(0,100));
}
}
}
public class test{
public static void main(string[] args){
book book = new book(5);
random random = new random();
string[] readernames = {"猪八戒","唐僧","沙和尚"};
string[] writernames = {"观音菩萨","孙悟空","玉皇大帝"};
thread[] readerthreads = new thread[3];
thread[] writerthreads = new thread[3];
for(int i = 0;i < 3;i++){
reader reader = new reader(book,random);
readerthreads[i] = new thread(new threadstart(reader.read));
readerthreads[i].name = readernames[i];
writer writer = new writer(book,random);
writerthreads[i] = new thread(new threadstart(writer.write));
writerthreads[i].name = writernames[i];
}
for (int i=0; i<3; i++){
readerthreads[i].start();
writerthreads[i].start();
}
}
}