/* cc thisfile.c -lthread -lpthread */ /* * This version of the program uses semaphore to protect the * shared variable. */ #include #include #include #include #include /* for semphares */ #define NO_SHARE 0 /* 0 means not shared among processes, used * in sem_init() */ //#define NUM_THREADS 5000 #define NUM_THREADS 10 void *work(void *); /* thread routine */ /* global variables */ int v = 0; // shared data sem_t lock; // semaphore lock int main(int argc, char *argv[]) { int i; int lock_value; /* value of the semaphore */ pthread_t tid[NUM_THREADS]; /* array of thread IDs */ sem_init(&lock, NO_SHARE, 1); /* initialize the semaphore lock */ sem_getvalue(&lock,&lock_value); /* retrieve the lock value */ printf("lock value in main() is %d\n", lock_value); for ( i = 0; i < NUM_THREADS; i++) pthread_create(&tid[i], NULL, work, NULL); for ( i = 0; i < NUM_THREADS; i++) pthread_join(tid[i], NULL); printf("main() reporting that all %d threads have terminated\n", i); printf("v should be %d, it is %d\n", NUM_THREADS, v); return (0); } /* main */ void * work(void *arg) { int lock_value; if (pthread_self() % 2 == 0) // even numbered thread, try to create race cond usleep(30); sem_wait(&lock); // allows only one process to update v at a time sem_getvalue(&lock,&lock_value); v ++; // CR sem_post(&lock); // release the lock so others can come into the CR printf("lock value in work() is %d\n", lock_value); return (NULL); }