//HW3 #include #include #include pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mcond = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condv = PTHREAD_COND_INITIALIZER; int box[4]; int count = 0; void *gcd(void *nums); void *work(void *tum); void *gcd(void *nums) { int a, b, d, org1, org2; char pair[20]; sscanf(nums, "%d, %d", &a, &b); org1 = a; org2 = b; box[3] = -1; int c = -1; int cnt = 0; while(c != 0) { if(b > a){ d = a; a = b; b = d; } pthread_mutex_lock(&mlock); box[0] = a; box[1] = b; box[2] = -1; while(box[2] < 0){ pthread_cond_signal(&condv); } cnt++; a = box[2]; b = box[1]; c = box[2]; pthread_mutex_unlock(&mlock); } count++; printf("Thread ID:%d \tGCD of %d & %d: %d after %d tries\n", pthread_self(), org1, org2, b, cnt); pthread_exit(NULL); } void *work(void *tnum) { int test; test = (int)tnum; while(count < (int)tnum) { pthread_cond_wait(&condv, &mcond); box[2] = (box[0] % box[1]); } } main(int argc, char** argv) { if(argc == 1 || argc % 2 != 1) { printf("give me pairs of numbers and I will give you GCDs\n"); exit(0); } else { clock_t c0, cl1; time_t t0, t1; t0 = time(NULL); c0 = clock(); printf("begin wall: %d\n", (long)t0); printf("begin clock: %d\n", (int)c0); int a1, b1, c1; int check = 1; int tnum = (argc/2); pthread_t threads[tnum]; pthread_t worker; int rc, t; char pair[20]; if(pthread_create(&worker, NULL, work, (void *)tnum)){ printf("ERROR"); } else{ printf("Creating Worker thread\n"); } for(t = 0; t < tnum; t++) { box[3] = 1; a1 = atoi(argv[check++]); b1 = atoi(argv[check++]); sprintf(pair, "%d, %d", a1, b1); printf("Creating thread\n"); rc = pthread_create(&threads[t], NULL, gcd, (void *)&pair); if(rc){ printf("ERROR"); exit(-1); } while(box[3] != -1); } for(t = 0; t < tnum; t++) { pthread_join(threads[t], NULL); } printf("ALL DONE\n"); t1 = time(NULL); c1 = clock(); printf("\nEND wall time:\t%1d\n", (long)(t1)); printf("END clock time:\t%f\n", (float)(cl1)); exit(0); } }