/*********************************************************************** * helloThreaded.c * * From https://computing.llnl.gov/tutorials/pthreads/. * Modified by Tom Kelliher * * This program demonstrates the pthreads library. To compile under * Linux, a command similar to * * gcc -o helloThreaded -lpthread helloThreaded.c * * should suffice. * * This program is a simple demonstration of the pthreads library. * The main thread creates NUM_THREADS child threads, each of which * prints a "Hello world" message. By performing a join on each child * thread, the main thread hangs around until each child thread has * exited. ***********************************************************************/ #include #include #include #define NUM_THREADS 10 /* Function prototypes */ void *printHello(void *); /*********************************************************************** * main() ***********************************************************************/ int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; /* Array to store thread IDs. */ long i; int rc; /* Return code from function call. */ for (i = 0; i < NUM_THREADS; i++) { printf("In main: creating thread %d.\n", i); /* Create a thread. The first argument is a pointer to a variable * of type pthread_t and is used to store the newly-created * thread's ID. The second argument is used to specify attributes * of the new thread. Passing a NULL pointer will result in the * use of default attributes. The third argument is a pointer * to the function that the thread will initially start in. This * function must take a single argument of type pointer to void and * must return a value of type pointer to void. The final argument * is the value to pass to the initial function. * * In this specific instance, each thread is passed its index * within the threads array; this value is used to identify the * various threads. */ rc = pthread_create(&threads[i], NULL, printHello, (void *) i); if (rc) { printf("ERROR; return code from pthread_create() is %d.\n", rc); exit(-1); } } /* Wait for each of the child threads to exit. The join call returns * immediately if the child has already exited. In this example, we * we are not using the return value mechanism available to us. */ for (i = 0; i < NUM_THREADS; i++) pthread_join(threads[i], NULL); printf("Main thread exiting.\n"); return 0; } /*********************************************************************** * printHello() ***********************************************************************/ void *printHello(void *threadid) { long tid; /* Thread ID */ /* threadid was originally an int, cast to (void *). Cast it back to * int. */ tid = (long) threadid; printf("Hello World! It's me, thread #%d!\n", tid); pthread_exit(NULL); /* Not returning a value. */ }