/* pthreads_sample.c Jeff Ondich, 6 March 2022 A simple threaded program that lets us see a typical use of threads. One thread is an extremely simple user interface thread (printing a prompt and waiting for a newline), while the other is a trivial "computational" thread, counting until the UI thread tells it to stop. The two threads communicate through the global variable time_to_quit. To compile on mantis: gcc -Wall -o pthreads_sample pthreads_sample.c -lpthread On some systems, you don't need to link the pthread library explicitly, so it looks like this instead: gcc -Wall -o pthreads_sample pthreads_sample.c */ #include #include #include #include bool time_to_quit = false; void *ui_thread_main(void *arg); void *worker_thread_main(void *arg); int main() { pthread_t ui_thread, worker_thread; // Spawn the threads if (pthread_create(&ui_thread, NULL, ui_thread_main, 0) != 0) { perror("Can't create UI thread"); exit(1); } if (pthread_create(&worker_thread, NULL, worker_thread_main, 0) != 0) { perror("Can't create worker thread"); exit(1); } // Detach the worker thread. This means that once the worker thread finishes, // all its associated resources will get cleaned up automatically. if (pthread_detach(worker_thread) != 0) { fprintf(stderr, "Failed to detach worker thread. I'm going to go pout.\n"); exit(1); } // Wait for the UI thread to return. If you don't wait for it, // we will return from main(), and thus shut down the whole // process, including the threads. pthread_join(ui_thread, NULL); return 0; } void *ui_thread_main(void *arg) { char buffer[100]; printf("[UI thread] Hit Enter when you're ready to be done\n"); fgets(buffer, 100, stdin); time_to_quit = true; return NULL; } void *worker_thread_main(void *arg) { long counter = 0; while(!time_to_quit) { counter++; } printf("[Worker thread] I counted this high: %ld\n", counter); return NULL; }