/* Creating and joining threads */ #define _GNU_SOURCE #define _REENTRANT #include #include #include #include #include #include int MAX=5; int my_rand( int, int ); void *say_it( void * ); int main(int argc, char *argv[]) { pthread_t thread_id[MAX]; int status, *p_status = &status; int i; setvbuf(stdout, (char *) NULL, _IONBF, 0); if ( argc > MAX+1 ) { // check arg list fprintf(stderr, "%s arg1, arg2, ... arg%d\n", argv[0], MAX); return 1; } printf("Displaying\n"); for (i = 0; i < argc-1; ++i) { // generate threads if( pthread_create(&thread_id[i],NULL,say_it,(void *)argv[i+1]) > 0) { fprintf(stderr, "pthread_create failure\n"); return 2; } } for (i=0; i < argc-1; ++i) { // wait for each thread if ( pthread_join(thread_id[i], (void **) p_status) > 0) { fprintf(stderr, "pthread_join failure\n"); return 3; } printf("\nThread %d returns %d", thread_id[i], status); } printf("\nDone\n"); return 0; } // Display the word passed a random # of times void * say_it(void *word) { int i; int numb = my_rand(2,6); printf("%s\t to be printed %d times.\n", (char *)word, numb); sleep(1); for (i=0; i < numb; ++i) { //sleep(1); printf("%s ", (char *) word); } sleep(4); return (void *) NULL; } // Generate a random # within given range int my_rand(int start, int range) { struct timeval t; gettimeofday(&t, (struct timezone *)NULL); return (int)(start+((float)range * rand_r((unsigned *)&t.tv_usec)) / (RAND_MAX+1.0)); }