//////////////////////////////////////////////////////////// // // mutexTester.c // // Jeff Ondich, 5/7/98 // // This program illustrates the use of the mutex_t // type in conjunction with Mach C-threads. If you // remove the mutex_lock() and mutex_unlock() calls, // then the parent and child threads can interrupt // each other in the midst of important business. // With the mutex_lock() and mutex_unlock() calls, // the parent and child can finish their important // business without interruption. // //////////////////////////////////////////////////////////// #include #include // Global variable(s) mutex_t lock; // Prototype(s) void Child( int childID ); int main( void ) { // This is C, not C++, so I need to declare local // variables up here. Our cc compiler is kind enough, // however, to allow me C++ comments. int i; // You have to tell Mach that you intend to use a // mutex_t variable before you actually use it. lock = mutex_alloc(); // Spawn a child thread that starts execution in the // function Child(). cthread_detach( cthread_fork( (cthread_fn_t)Child, (any_t)0 ) ); // This code is executed only by the parent, though // it bears an uncanny resemblance to the code // executed by the child. while( 1 == 1 ) { // Fool around for a while for( i=0; i < 1000000; i++ ) { } // Now do some serious business, reporting // when the business starts and when it // finishes. Lock the lock first, to // make sure you don't get interrupted. mutex_lock( lock ); printf( "\tPARENT START\n" ); for( i=0; i < 1000000; i++ ) { } printf( "\tPARENT STOP\n" ); mutex_unlock( lock ); } } void Child( int childID ) { int i; while( 1 == 1 ) { // Fool around for a while for( i=0; i < 1000000; i++ ) { } // Now do some serious business, reporting // when the business starts and when it // finishes. Lock the lock first, to // make sure you don't get interrupted. mutex_lock( lock ); printf( "Child %d start\n", childID ); for( i=0; i < 1000000; i++ ) { } printf( "Child %d stop\n", childID ); mutex_unlock( lock ); } }