// threadtest.cc // Implements multiple readers and writers accessing a single // integer object. // #include "copyright.h" #include "system.h" #include "malloc.h" int target; //the shared variable // The class defining a writer.....remember the writer increments the value of target class Writer { public: // Construct a writer whose unique id is tag Writer(int tag); // Let the writer write. void run (); private: int id; // Writer's unique identifier }; // The class defining a reader class Reader { public: // Construct a reader whose unique id is tag Reader (int tag); // Let the reader read. void run (); private: int id; // Reader's unique identifier }; /* The following two procedures are hacks you'll need because Nachos fork routine takes a function, not a method. The write function is passed a Writer object and calls its run method. The fork routine requires the function being called to pass an int. When you call fork, you need to coerce the Writer object into an int. Here, we coerce it back. read is similar, but works for readers. */ void write(int p) { ((Writer *)p)->run(); } void read(int c) { ((Reader *)c)->run(); } /* The body of ThreadTest is replaced with code to run writer/reader. */ void ThreadTest() { DEBUG('t', "Entering writer/reader"); // Get all the necessary input from the user. printf ("Please enter the number of writers: "); int numWriters; scanf ("%d", &numWriters); if (numWriters <= 0) { printf ("The number of writers must be non-negative.\n"); exit (-1); } Thread *t; Writer *p; for (int i = 0; i < numWriters; i++) { // Start the writers } printf ("Please enter the number of readers: "); int numReaders; scanf ("%d", &numReaders); if (numReaders <= 0) { printf ("The number of readers must be non-negative.\n"); exit (-1); } Reader *c; for (int j = 0; j < numReaders; j++) { // Start the readers } // Keep the main thread alive. You'll need to kill this program // with control-c or else figure out when it would be safe to stop. while (true) { currentThread->Yield(); } } Writer::Writer (int which) { id = which; } Void Writer::run () { while(true) { //increment the shared integer printf("Writer %d incremented integer to %d\n",id,target); } } Reader::Reader (Buffer *buf, int which) { id = which; } void Reader::run () { while (true) { // Read the shared integer printf ("Reader %d integer value is %d\n", id, target); } }