[Original] C # writer writer (selfish reader)

xiaoxiao2021-03-06  61

// self-privacy reader's writer write system; use system.threading; public class book {private int [] pages; private object mutex = new object (); // Control to ReaderCount Visit Private Object DB = New Object ( ); // Control access to 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) {// checks if it is 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 (db) {pages [index] = value; console.writeline (thread.currentthread.name "Write" Value " (INDEX 1) " Page ") DisplayContent ();}}} private void displayContent () {console.writeLine ("{0, -35}", "book content is:"); for (int i = 0; i

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); // Write thread.sleep (Rand.Next (0,300));}}}

Public class test {public static void main (string [] args) {book book = new book (5); random random = new random (); string [] readernames = {"Pig Eight Rings", "Tang Yan", "Shahe Shang" }; String [] Writernames = {"Guanyin Bodhisattva", "Sun Wukong", "Yu 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-111708.html

New Post(0)