/* pthreads-with-race.c Jeff Ondich, 12 April 2004 Updated 20 May 2019 A simple threaded program with a shared integer and a race condition. To compile: gcc -Wall -o pthreads_with_race pthreads_with_race.c On some systems, you might need: gcc -Wall -o pthreads_with_race pthreads_with_race.c -lpthreads */ #include #include #include int gSharedInteger = 0; 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 ); } /* Wait for threads to return. If you don't wait for them, the process will return from main(), and thus shut down the whole process, including the threads. */ pthread_join(threadA, NULL); pthread_join(threadB, NULL); return 0; } void *threadMainA(void *arg) { while(1) { gSharedInteger = 25; } return NULL; } void *threadMainB(void *arg) { while(1) { gSharedInteger = 37; if (gSharedInteger != 37) { fprintf(stderr, "Uh-oh. Race condition.\n"); fflush(stderr); } } return NULL; }