/* * Illustrate two threads working the same function */ #include #include #include #include // for gettimeofday int max; // number of times to increment the variable per thread volatile int balance = 0; // shared global variable struct timeval start, end; // // syntax is: int gettimeofday ( struct timeval *tp , struct timezone *tz ) // only timeval important timezone not needed, can be NULL // timeval struct has: // tv_sec : It is the number of seconds since the epoch. // tv_usec :It is additional microseconds after number of seconds calculation since the epoch. . // // void * mythread(void *arg) { char *letter = arg; int i; // stack (private per thread) printf("%s: begin [addr of i: %p]\n", letter, &i); for (i = 0; i < max; i++) { balance = balance + 1; // shared among threads } printf("%s: done\n", letter); return NULL; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: t1 \n"); exit(1); } gettimeofday(&start, NULL); printf("seconds : %ld microseconds : %ld\n", start.tv_sec, start.tv_usec); max = atoi(argv[1]); pthread_t p1, p2; printf("main: begin [balance = %d] [%p]\n", balance, &balance); pthread_create(&p1, NULL, mythread, "A"); // P is capitalized for our textbook only! pthread_create(&p2, NULL, mythread, "B"); // p is lower case out in the wild. pthread_join(p1, NULL); // join waits for the threads to finish pthread_join(p2, NULL); printf("main: done\n [balance: %d]\n [should: %d]\n", balance, max*2); gettimeofday(&end, NULL); printf("seconds : %ld microseconds : %ld\n", end.tv_sec, end.tv_usec); printf("elapsed time is: %ld seconds and %ld microseconds\n", end.tv_sec - start.tv_sec, end.tv_usec - start.tv_usec); return 0; }