/* Program to compute sum of the first N positive integers */ /* This version uses four threads of control: */ /* - main thread does setup and final output */ /* - worker1 thread computes the sum for odd integers */ /* - worker2 thread computes the sum for even integers */ /* - checker thread uses the formula to check */ /* Based on example from page 161 of the textboook. CLW */ /* This version is somewhat sloppy in its use of shared global sum */ #include #include int sum; /* global variable shared by all threads */ int checksum; /* global variable shared by all threads */ void *runner1(void *param); /* the main worker thread for odds */ void *runner2(void *param); /* the main worker thread for events */ void *checker(void *param); /* the main checker thread */ int main(int argc, char *argv[]) { pthread_t tid1, tid2, tid3; /* thread identifier */ pthread_attr_t attr; /* set of thread attributes */ int limit; /* check command line argument */ if( argc != 2 ) { fprintf(stderr, "Usage: ./summer5 value\n"); return -1; } limit = atoi(argv[1]); if( limit < 0 ) { fprintf(stderr, "Value must be non-negative!\n"); return -1; } /* get the default attributes */ pthread_attr_init(&attr); /* create the first worker thread */ pthread_create(&tid1, &attr, runner1, argv[1]); /* create the second worker thread */ pthread_create(&tid2, &attr, runner2, argv[1]); /* create the checker thread */ pthread_create(&tid3, &attr, checker, argv[1]); /* wait for the first worker thread to exit */ pthread_join(tid1, NULL); /* wait for the second worker thread to exit */ pthread_join(tid2, NULL); /* wait for the checker thread to exit */ pthread_join(tid3, NULL); /* output the final result */ printf("The sum of the first %d positive integers is: %d\n", limit, sum); } /* One thread will begin control in this function. */ /* It does all the work to compute the required sum. */ /* This one does only the odd integers. */ void *runner1(void *param) { int i; int upper; /* initialize */ upper = atoi(param); sum = 0; /* main loop */ for( i = 1; i <= upper; i += 2 ) { sum += i; } pthread_exit(0); } /* The other thread will begin control in this function. */ /* It does all the work to compute the required sum. */ /* This one does only the even integers. */ void *runner2(void *param) { int i; int upper; /* initialize */ upper = atoi(param); sum = 0; /* main loop */ for( i = 0; i <= upper; i += 2 ) { sum += i; } pthread_exit(0); } /* The other thread will begin control in this function. */ /* It uses the known formula to check the sum answer. */ void *checker(void *param) { int answer; int n; /* initialize */ n = atoi(param); answer = n * (n + 1) / 2; /* output the formula result */ printf("The sum of the first %d positive integers should be: %d\n", n, answer); pthread_exit(0); }