[Original] C # writer write writer (fair competition reader)

xiaoxiao2021-03-06  63

// reader writer problem

Using system; using system.threading;

Public class book {

Private int [] pages; private bool awriterwait = false; private int readyercount = 0;

Private Object (); // Controls Access to ReaderCount Private Object DB = New Object (); // Controls Visit Object Obj = New Object (); // Controls Access to AWRITERWAIT

Public book (int Numofpages) {pages = new int {pages = new int [numofpages];

Public int numofpages {get {return pages.length; // constant, no need to sync}}

Public int this [int index] {while (awriterwait) {monitor.wait (obj);}}

Lock // check for the first reader ReaderCount ; if (Readercount == 1) Monitor.Enter (DB);} int valuecopy = pages [index]; // Read a data

Console.Writeline (Thread.currentthRead.Name "read the" (INDEX 1) "page, the data he read is" valuecopy);

DisplayContent ();

Lock (Mutex) {readercount -; if (readercount == 0) Monitor.exit (db);

Return Valuecopy;} set {lock (obj) {awriterwait = true;

Lock (dB) {// Blocks other writers from writing pages [index] = value; console.writeline (thread.currentthread.name "Write" Value " (INDEX 1) "Page"); DisplayContent ();} lock (obj) {awriterwait = false; monitor.pulseall (obj); // Notification Wait Reader}}} private void displayContent ()} private void displayContent ()} private void displayContent ()} private void displayContent () 35} "", "The content is:"); for (int i = 0; i

Public class reader {private book; private randem; 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; 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 class test}}} public class test}}} (String [] args) {book book = new book (5); random random = new random (); string [] readernames = {"Pig Eight Rings", "Tang Yan", "Sand monk"}; String [] Writernames = { "Guanyin Bodhisattva", "Sun Wukong", "Jade Emperor"};

Thread [] readERTHREADS = New Thread [3]; thread [] Writerthreads = New Thread [3];

For (int i = 0; i <3; i ) {reader reader = new reader; readERTHREADS [i] = new thread (Reader.Read); readERTHREADS [i] .Name = readernames [I]; Writer Writer = New Writer (Book, Random); Writerthreads [i] = new thread (Writer.Write); Writerthreads [i] .name = Writernames [i];

} For (int i = 0; i <3; i ) {readERTHREADS [I] .Start (); Writerthreads [i] .start ();}}}

转载请注明原文地址:https://www.9cbs.com/read-111707.html

New Post(0)