/* criticalsection2.c with semaphore operations implemented using a pipe */ #include #include #include #include #include #include #include #include #define THREADS 5 int sem[2]; /* pipe file descriptor for use as a semaphore */ void P( int sem[] ){ char buf[1]; read( sem[0], &buf, 1 ); } void V( int sem[] ){ char buf[1] = { 'a' }; write( sem[1], &buf, 1 ); } void *threadfunc( void * arg ) { /* function for each thread */ int *me; me = (int *) arg; P( sem ); printf( "Thread %d running!! Line 1\n", *me ); printf( "Thread %d running!! Line 2\n", *me ); printf( "Thread %d running!! Line 3\n", *me ); V( sem ); pthread_exit( NULL ); } int main( void ) { int i; pthread_t tid[THREADS]; int id[THREADS]; pipe( sem ); /* create "semaphore" and */ V( sem ); /* initialise to 1 */ for( i=0; i