// class constructor // public MutexHandler(bool case1, Mutual_Exclusion_Form form) { // if true, then use case 1 operation // // Ricart & Agrawalas mutual exclusion algorithm, one person on bridge at a time. Everyone eventually allowed to cross (via queue) // parentForm = form; populateHandles(case1); // Create handles data structure, needed for all operational cases // this.setInitialData(); // Sets inital thread data in the shared memory // // Common init code between case 1 and case 2 // parentForm.rInsert(Color.Red); parentForm.rInsert(Color.Red); parentForm.lInsert(Color.Blue); parentForm.lInsert(Color.Blue); // Specific case code execution // if (case1) { // FOR CASE 1 -> EXECUTE MUTUAL EXCLUSION ALGORITHM // Richart_Agrawala(form); } // if false, design protocol 2 states that bridge crossings allowed directionally in sync, but no job indefinately prevented from crossing else { // FOR CASE 2 -> EXECUTE MUTUAL EXCLUSION ALGORITHM // Multi_Bridge(form); } }
void Richart_Thread(int number) { if (endIt) { return; } // function code goes here for a thread // int myThreadNr = number; while (true) // infinitely execute unil terminated // { Thread.Sleep(parentForm.getSliderValue()); // sleeps for ms value indicated on slider (100ms - 500ms range) // if (sharedMemoryLock.WaitOne()) { if (!sharedMemory[myThreadNr].request) { // Have critical section to shared memory, set shared memory for bridge lock, then release Mutex and give other threads opportunity to respond // sharedMemory[myThreadNr].request = true; sharedMemory[myThreadNr].timeStamp = DateTime.Now; sharedMemoryLock.ReleaseMutex(); } else { sharedMemoryLock.ReleaseMutex(); } } // only needed if entering the bridge // bool result = false; string direction = string.Empty; // ^^ only needed if entering the bridge // if (sharedMemoryLock.WaitOne()) { result = enterBridge(myThreadNr); if (result) { sharedMemory[myThreadNr].CS = true; sharedMemory[myThreadNr].request = false; direction = sharedMemory[myThreadNr].direction; } sharedMemoryLock.ReleaseMutex(); } // go onto the bridge if true // if (result) { switch (direction) { case "L": Color col = parentForm.rShift(); parentForm.iMiddle(col); Thread.Sleep(parentForm.getSliderValue()); Color colT = parentForm.rMiddle(); parentForm.lInsert(colT); if (sharedMemoryLock.WaitOne()) { sharedMemory[myThreadNr].CS = false; sharedMemory[myThreadNr].direction = "R"; sharedMemoryLock.ReleaseMutex(); } break; case "R": Color col2 = parentForm.lShift(); parentForm.iMiddle(col2); Thread.Sleep(parentForm.getSliderValue()); Color colT2 = parentForm.rMiddle(); parentForm.rInsert(colT2); if (sharedMemoryLock.WaitOne()) { sharedMemory[myThreadNr].CS = false; sharedMemory[myThreadNr].direction = "L"; sharedMemoryLock.ReleaseMutex(); } break; } } } }