#include #include #include int sum; //global variable used by both threads void *runner(void *param); // the thread function int main(int argc, char * argv[]) { // main is the initial thread of execution pthread_t tid; //the id of a created thread later pthread_attr_t attr; //attributes to create a thread if(argc != 2) { //do we have the right number of arguments? fprintf(stderr,"Syntax:./thread value\n"); return -1; } if(atoi(argv[1]) < 0) { // we're doing a sum from 0 to "n" fprintf(stderr,"Argument %d must be >= 0\n",atoi(argv[1])); return -1; } pthread_attr_init(&attr); //set up the initial attributes //pthread_create creates a new thread //the id of the new thread is "tid" //the new thread will run the function "runner" //with an an argument "argv[1]" //the argument is passed as a void * and thus must be handled. // ALL arguments to a thread function must be an address pthread_create(&tid,&attr,runner,argv[1]); //create the new thread //pthread_join is like a "wait" This call says: //wait until the thread with id "tid" is finished before continuing //this thread of execution pthread_join(tid,NULL); printf("sum = %d\n",sum); } void *runner(void *param) { int i,upper; char *p = ((char *)param); //transform the input param upper = atoi(p); //get the integer assoc with this string sum = 0; for(i = 1; i <= upper; i++) //calc sum from i = 1 to upper sum+=i; pthread_exit(0); // exit this thread }