/* helloThreads.c * This is a multi-threaded "hello world" * Each thread prints "hello". and they are not guaranteed to do so in the order they were created. * * gcc -o hello -lpthread helloThread.c * */ #include #include #include #define NUM_THREADS 5 typedef struct { int id; } threadInfo; // the main function for a pthread must return a void * and have a single void* as its input void *hello_thread(void *threadinfo) { threadInfo *ti = (threadInfo *) threadinfo; printf("Thread %d", ti->id ); printf( " saying Hello!\n"); pthread_exit(NULL); } int main () { int i; threadInfo ti[NUM_THREADS]; pthread_t thread[NUM_THREADS]; // Set up the parameters for each thread for (i = 0; i < NUM_THREADS; i++) ti[i].id = i; // Get the threads going for (i = 0; i < NUM_THREADS; i++) { pthread_create(&(thread[i]), NULL, hello_thread, &(ti[i])); } // Join up with them. This will wait until they are done. // If we don't have this hear, then the main program ends before // the threads complete their tasks for (i = 0; i < NUM_THREADS; i++) pthread_join(thread[i], NULL); // If we sleep instead of joining, that gives some threads time to finish // their tasks //sleep(1); return 0; }