primes.c (1104B)
1 #include <stdbool.h> 2 #include <pthread.h> 3 4 #define NTHREADS 16 5 6 bool isprime(int); 7 void *pthread_routine(void *); 8 9 struct interval { int low; int high; int count; }; 10 11 int primes_in_range(int low, int high, void (*log)(const char *)) { 12 pthread_t threads[NTHREADS]; 13 struct interval args[NTHREADS]; 14 15 if (low < 0 || high < low) 16 return 0; 17 18 int interval_size = (high-low)/NTHREADS + 1; 19 for (int i = 0; i < NTHREADS; i++) { 20 args[i].low = low + i*interval_size; 21 args[i].high = args[i].low + interval_size; 22 pthread_create(&threads[i], NULL, pthread_routine, &args[i]); 23 } 24 25 log("All threads have started, computing..."); 26 27 int result = 0; 28 for (int i = 0; i < NTHREADS; i++) { 29 pthread_join(threads[i], NULL); 30 result += args[i].count; 31 } 32 33 return result; 34 } 35 36 bool isprime(int n) { 37 if (n < 2) 38 return false; 39 40 for (int i = 2; i*i <= n; i++) 41 if (n % i == 0) 42 return false; 43 return true; 44 } 45 46 void *pthread_routine(void *arg) { 47 struct interval *interval = arg; 48 49 interval->count = 0; 50 for (int i = interval->low; i < interval->high; i++) 51 if (isprime(i)) 52 interval->count++; 53 54 return NULL; 55 }