/* Compile, for example: gcc pthread_example.c -lpthread -o pthread_example */ #include #include /* variable sum is shared by the threads */ int sum; /* thread */ void *runner(void *param); /* First thread */ main(int argc, char *argv[]) { /* Thread identifier */ pthread_t tid; /* Attributes for a thread (stack size, scheduling ...) */ pthread_attr_t attr; if (argc !=2){ fprintf(stderr,"Usage: %s \n",argv[0] ); exit(); } if (atoi(argv[1]) < 0) { fprintf(stderr,"(%d) must be >= 0\n",atoi(argv[1])); exit(); } /* Set attributes (default attributes are used) */ pthread_attr_init(&attr); /* Create a separate thread */ /* Pass a thread identifier (tid), attributes (attr), name of the */ /* function where the new thread will begin execution (runner), */ /* and the integer parameter provided on the command line (argv[1]) */ /* Now program has two threads: main and runner */ pthread_create(&tid,&attr,runner,argv[1]); /* main waits runner thread using pthread_join */ pthread_join(tid,NULL); /* print results of summing */ printf("Sum = %d\n",sum); } /* Second thread */ void *runner(void *param) { int upper = atoi(param); int i; sum = 0; if (upper > 0) { for (i=1; i<=upper; i++) sum +=i; } /* runner thread completes here */ pthread_exit(0); }