/* * Illustrate two threads working the same function */ #include #include #include int max; // number of times to increment the variable per thread volatile int balance = 0; // shared global variable 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); } 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); return 0; }