[原创]C#编写的读者写者问题(自私的读者)

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 hippoz 的 blog

// 自私读者的 读者写者问题
using system;
using system.threading;
public class book{
 private int[] pages;
 
 private object mutex = new object(); // 控制对 readercount 的访问
 private object db = new object(); // 控制对 pages 的访问

 private int readercount = 0;
 
 public book(int numofpages){
  pages = new int[numofpages];
 }

 public int numofpages{
  get{
   return pages.length;
  }
 }

 public int this[int index]{
  get{
   lock(mutex){
    //检查是否为第一个读者
    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(db){
    pages[index] = value;
    console.writeline( thread.currentthread.name + "把" + value + "写到第" + (index + 1) + "页");
    displaycontent();
   }
  }
 }
 
 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();
  } 
 }
}

本文关键:[原创]C#编写的读者写者问题(自私的读者)
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top