/* Calculates number of primes between 1 and 20 million. * CS 226 Lab 6 */ #include #include #include #include #include void failif(bool cond); //returns whether num is prime bool isPrime(long num) { int limit = (int) sqrt(num); for(long i=2; i<=limit; i++) { if(num % i == 0) return false; } return true; } // start should be odd. void count_primes (long *pCount, long start, long finish) { while(start < finish) { if(isPrime(start)) { ++*pCount; } start += 2; } } struct prime_arg { long *pCount; long start, finish; }; void *prime_thread (void *arg) { struct prime_arg *parg = (struct prime_arg *) arg; count_primes (parg->pCount, parg->start, parg->finish); return parg->pCount; } int main () { long pCount = 1; //(starting with 2) pthread_t t1, t2; struct prime_arg t1arg = { &pCount, 3, 10000000 }; struct prime_arg t2arg = { &pCount, 10000001, 20000000 }; failif (pthread_create(&t1, NULL, prime_thread, &t1arg) != 0); failif (pthread_create(&t2, NULL, prime_thread, &t2arg) != 0); printf ("%ld primes found", pCount); } // Checks if value is true, and if so, terminates void failif(bool cond) { if (cond) { perror("primes"); exit(EXIT_FAILURE); } }