#include #include #include #include "my_timing.h" typedef struct { int id; int N; int chunk_size; int num_threads; int count; } ThreadInfo; // check whether a number is a prime // return 1 if it is a prime, else 0 int is_prime (int n) { if (n < 2) return 0; if (n == 2) return 1; if (n%2 == 0) return 0; for (int i = 3; i < n; i += 2) { if (n%i == 0) return 0; } return 1; } // worker func: check the primes in // the given range void *thread_count_primes (void *thread_info) { double t1 = get_time_sec(); ThreadInfo *ti = (ThreadInfo *)thread_info; int start = ti->chunk_size * ti->id; for (int i = start; i < ti->N; i = i + ti->chunk_size*ti->num_threads ) { for (int j = 0; j < ti->chunk_size; j++) { if (is_prime(i+j)) ti->count++; } } double t2 = get_time_sec(); printf( "Thread %d took %f seconds\n", ti->id, t2-t1 ); pthread_exit(NULL); } int main (int argc, char** argv) { int N = 1000000; int NUM_THREADS = 4; int CHUNK_SIZE = 8; if (argc > 1) NUM_THREADS = atoi(argv[1]); double t1, t2; ThreadInfo srt[NUM_THREADS]; pthread_t thread[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { srt[i].id = i; srt[i].chunk_size = CHUNK_SIZE; srt[i].N = N; srt[i].num_threads = NUM_THREADS; srt[i].count = 0; } t1 = get_time_sec(); // create threads for (int i = 0; i < NUM_THREADS; i++) { pthread_create(&thread[i], NULL, thread_count_primes, &srt[i]); } // join threads for (int i = 0; i < NUM_THREADS; i++) { pthread_join(thread[i], NULL); } // sum counts int count = 0; for (int i = 0; i < NUM_THREADS; i++) { count += srt[i].count; } t2 = get_time_sec(); printf("There are %d primes not larger than %d\n",count, N); printf("It took %f seconds to count the number with %d threads\n", t2 - t1, NUM_THREADS); return EXIT_SUCCESS; }