/* Program to compute sum of the first N positive integers */ /* This version uses two threads of control: */ /* - main thread does setup and final output */ /* - worker thread computes the sum */ /* Based on example from page 161 of the textboook. CLW */ /* Usage: cc -o summer2 summer2.c -pthread */ /* ./summer2 value */ #include #include int sum; /* global variable shared by all threads */ void *runner(void *param); /* the main worker thread */ int main(int argc, char *argv[]) { pthread_t tid; /* thread identifier */ pthread_attr_t attr; /* set of thread attributes */ int limit; /* check command line argument */ if( argc != 2 ) { fprintf(stderr, "Usage: ./summer2 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 thread */ pthread_create(&tid, &attr, runner, argv[1]); /* wait for the thread to exit */ pthread_join(tid, NULL); /* output the final result */ printf("The sum of the first %d positive integers is: %d\n", limit, sum); } /* The thread will begin control in this function. */ /* It does all the work to compute the required sum. */ void *runner(void *param) { int i; int upper; /* initialize */ upper = atoi(param); sum = 0; /* main loop */ for( i = 1; i <= upper; i++ ) { sum += i; } pthread_exit(0); }