// threadtest.cc // Simple test case for the threads assignment. // // Create two threads, and have them context switch // back and forth between themselves by calling Thread::Yield, // to test the mutex lock synchronization primitive. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "synch.h" //---------------------------------------------------------------------- // shared_data - global shared data. // shared_data_lock - a mutual exclusion lock that protects it. //---------------------------------------------------------------------- int shared_data = 0; Lock shared_data_lock("shared data lock"); //---------------------------------------------------------------------- // SyncThread // A synchronization test case: incrementing shared_data five times. // // "which" is simply a number identifying the thread. //---------------------------------------------------------------------- void SyncThread(int which) { int num; for (num = 0; num < 5; num++) { // incrementing shared_data by one, protected by a mutex lock shared_data_lock.Acquire(); int local_copy = shared_data; currentThread->Yield(); // causing the scheduler to choose another // runnable thread to run if any exists local_copy ++; shared_data = local_copy; shared_data_lock.Release(); printf("*** thread %d incrementing shared_data to %d\n", which, shared_data); } } //---------------------------------------------------------------------- // ThreadTest // Set up a synchronization test between two threads, by forking a thread // to call SyncThread, and then calling SyncThread ourselves. //---------------------------------------------------------------------- void ThreadTest() { DEBUG('t', "Entering SyncTest"); Thread *t = new Thread("forked thread"); t->Fork(SyncThread, 1); SyncThread(0); }