// Compile: gcc -o semex1.exe -pthread semex1.c #include #include #include // Using Posix threads #include // Using Posix semaphores // prototype for thread function void *handler ( void *ptr ); // global variables sem_t binsem; //The semaphore will be used as a binary semaphore int counter; /* shared variable */ int main() { int i[2]; pthread_t thread_a; pthread_t thread_b; i[0] = 0; /* argument to threads */ i[1] = 1; sem_init(&binsem, 0, 1); // initialize semaphore to 1, second param = 0 - semaphore is local */ // should check that the thread has been successfully created by checking return value of // pthread_create() pthread_create (&thread_a, NULL, handler, (void *) &i[0]); pthread_create (&thread_b, NULL, handler, (void *) &i[1]); // wait for all threads to finish before destroying the semaphore pthread_join(thread_a, NULL); pthread_join(thread_b, NULL); sem_destroy(&binsem); // destroy semaphore // exit(0); } //Function that each thread executes void *handler ( void *ptr ) { int value, x; x = *((int *) ptr); printf("Thread %d: Waiting to enter critical region...\n", x); sem_wait(&binsem); //acquire the semaphore /* START CRITICAL REGION */ printf("Thread %d: Now in critical region...\n", x); sem_getvalue(&binsem, &value); printf("The value of the semaphore is %d\n", value); printf("Thread %d: Counter Value: %d\n", x, counter); printf("Thread %d: Incrementing Counter...\n", x); counter++; printf("Thread %d: New Counter Value: %d\n", x, counter); printf("Thread %d: Exiting critical region...\n", x); /* END CRITICAL REGION */ sem_post(&binsem); /* up semaphore */ pthread_exit(NULL); /* exit thread */ }