/* * "hello world" program: * * command-line argument gives number of threads. */ #include #include #include void * thread_fcn(void * thread_arg); /* ---- main program ---- */ int main(int argc, char* argv[]) { int * threadIDs; pthread_t * threads; char* usage_fmt = "usage: %s number_of_threads\n"; /* process command-line arguments */ char* end_ptr_for_strtol; if (argc != 2) { fprintf(stderr, usage_fmt, argv[0]); exit(EXIT_FAILURE); } int num_threads = strtol(argv[1], &end_ptr_for_strtol, 10); if (*end_ptr_for_strtol != '\0') { fprintf(stderr, usage_fmt, argv[0]); exit(EXIT_FAILURE); } /* * Set up IDs for threads (need a separate variable for each since they're * shared among threads). */ threadIDs = malloc(num_threads * sizeof(*threadIDs)); for (int i = 0; i < num_threads; ++i) threadIDs[i] = i; /* Start num_threads new threads, each with different ID. */ threads = malloc(num_threads * sizeof(*threads)); for (int i = 0; i < num_threads; ++i) pthread_create(&threads[i], NULL, thread_fcn, (void *) &threadIDs[i]); printf("all threads launched\n"); /* Wait for all threads to complete. */ for (int i = 0; i < num_threads; ++i) pthread_join(threads[i], NULL); printf("all threads complete\n"); /* Clean up and exit. */ free(threadIDs); free(threads); return EXIT_SUCCESS; } /* ---- code to be executed by each thread ---- */ void * thread_fcn(void * thread_arg) { int myID = * (int *) thread_arg; fprintf(stdout, "hello, world, from thread %d\n", myID); pthread_exit((void* ) NULL); }