/** * A pthread program illustrating how to * create a simple thread and some of the pthread API * This program implements the summation function where * the summation operation is run as a separate thread. * * gcc thrd.c -lpthread * * Figure 4.6 * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Seventh Edition * Copyright John Wiley & Sons - 2005. */ /* Modified by Krishna Sivalingam - Feb. 2006 */ #include #include int sum; /* this data is shared by the thread(s) */ double prod; /* this data is shared by the thread(s) */ void *runner1(void *param); /* the thread */ void *runner2(void *param); /* the thread */ int main(int argc, char *argv[]) { pthread_t tid1, tid2; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ if (argc != 2) { fprintf(stderr,"usage: a.out \n"); /*exit(1);*/ return -1; } if (atoi(argv[1]) < 0) { fprintf(stderr,"Argument %d must be non-negative\n",atoi(argv[1])); /*exit(1);*/ return -1; } /* get the default attributes */ pthread_attr_init(&attr); /* create the thread for summation */ pthread_create(&tid2,&attr,runner2,argv[1]); pthread_create(&tid1,&attr,runner1,argv[1]); /* create the thread for factorial */ /* now wait for threads to exit */ pthread_join(tid1,NULL); pthread_join(tid2,NULL); printf("sum = %d; prod = %.0lf\n",sum, prod); } /** * The thread will begin control in this function */ void *runner1(void *param) { int i, upper = atoi(param); sum = 0; /* Shared global variable. */ if (upper > 0) { for (i = 1; i <= upper; i++) sum += i; } fprintf(stdout," Thread 1 sez: %.0lf\n", prod); pthread_exit(0); } /** * The thread will begin control in this function */ void *runner2(void *param) { int i, upper = atoi(param); prod = 1.0; fprintf(stdout," Thread 2: %d\n", sum); if (upper > 0) { for (i = 1; i <= upper; i++) prod *= i; } pthread_exit(0); }