/* pthreads_without_race.c Jeff Ondich, 29 May 2019 A simple threaded program with a shared integer, using a mutex to prevent the obvious race condition. To compile: gcc -Wall -o pthreads_without_race pthreads_without_race.c On some systems, you might need to do this: gcc -Wall -o pthreads_without_race pthreads_without_race.c -lpthread */ #include #include #include int gSharedInteger = 0; pthread_mutex_t gLock = PTHREAD_MUTEX_INITIALIZER; void *threadMainA(void *arg); void *threadMainB(void *arg); int main() { pthread_t threadA, threadB; /* Spawn the threads. */ if (pthread_create(&threadA, NULL, threadMainA, 0) != 0) { perror("Can't create thread A"); exit(1); } if (pthread_create(&threadB, NULL, threadMainB, 0) != 0) { perror( "Can't create thread B" ); exit( 1 ); } pthread_join(threadA, NULL); pthread_join(threadB, NULL); return 0; } void *threadMainA(void *arg) { while(1) { pthread_mutex_lock(&gLock); gSharedInteger = 25; pthread_mutex_unlock(&gLock); } return NULL; } void *threadMainB(void *arg) { while(1) { pthread_mutex_lock(&gLock); gSharedInteger = 37; if (gSharedInteger != 37) { fprintf(stderr, "Uh-oh\n"); fflush(stderr); } pthread_mutex_unlock(&gLock); } return NULL; }