/* * "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[]) { if (argc < 2) { fprintf(stderr, "usage %s numthreads\n", argv[0]); return EXIT_FAILURE; } char *endptr; int numthreads = strtol(argv[1], &endptr, 10); if ((*endptr != '\0') || (numthreads <= 0)) { fprintf(stderr, "numthreads must be positive integer\n"); return EXIT_FAILURE; } int * threadIDs; pthread_t * threads; /* * Set up IDs for threads (need a separate variable for each since they're * shared among threads). */ threadIDs = malloc(numthreads * sizeof(*threadIDs)); for (int i = 0; i < numthreads; ++i) threadIDs[i] = i; /* Start numthreads new threads, each with different ID. */ threads = malloc(numthreads * sizeof(*threads)); for (int i = 0; i < numthreads; ++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 < numthreads; ++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); }