#include // printf #include // EXIT_SUCCESS #include // M_PI, fabs #include #include "pi_shared.h" int main(int argc, char* argv[]) { int seed; int N; int hits; double my_pi; int number_of_workers; int N_per_worker; // get parameters from command line arguments read_arguments(&seed, &N, argc, argv); // create OMP_NUM_THREADS threads // every thread will have its own hits variable (reduction implies private keyword) // after the parallel section, a single hits variable will remain, // holding the sum of all thread private hits variables #pragma omp parallel reduction(+:hits) { // divide the workload equally among threads number_of_workers = omp_get_num_threads(); N_per_worker = N / number_of_workers; N = N_per_worker * number_of_workers; // generate N_per_worker random coordinates, get number of hits // (see count_hits() function for details) // please note that every thread will start with a different seed value hits = count_hits(seed + omp_get_thread_num(), N_per_worker); } // estimate PI based on following assumptions // area of circle = PI * r^2 ~= hits // area of square around circle = (2 * r)^2 ~= N // r = 1 my_pi = 4. * ((double) hits / (double) N); // print seed, N, number_of_workers, result, error printf("%d\t%d\t%d\t%f\t%f\n", seed, N, number_of_workers, my_pi, fabs(my_pi-M_PI)); return EXIT_SUCCESS; }