/* pthreads_create.c Jeff Ondich, 29 May 2019 A simple threaded program that lets us see the threads taking turns. To compile: gcc -Wall -o pthreads_create pthreads_create.c On some systems, you might need: gcc -Wall -o pthreads_create pthreads_create.c -lpthreads */ #include #include #include 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) { int counter = 0; while(1) { counter++; if (counter % 1000000 == 0) { fprintf(stderr, "Thread A: %d\n", counter); fflush(stderr); } } return NULL; } void *threadMainB(void *arg) { int counter = 0; while(1) { counter++; if (counter % 1000000 == 0) { fprintf(stderr, "Thread B: %d\n", counter); fflush(stderr); } } return NULL; }