Skip to content

Instantly share code, notes, and snippets.

@feyyazesat
Last active April 14, 2017 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feyyazesat/c4a172c848933d17271351d901f2e29b to your computer and use it in GitHub Desktop.
Save feyyazesat/c4a172c848933d17271351d901f2e29b to your computer and use it in GitHub Desktop.
parallel programming : pi calculation.
#include <stdio.h>
#include <omp.h>
double piCalculation() {
static int num_total_steps = 100000;
int num_steps = (num_total_steps / omp_get_num_threads());
double step;
double sum = 0.0;
double execution_time = omp_get_wtime();
step = 1.0 / (double) num_total_steps;
#pragma omp parallel num_threads(1)
{
int i;
double x;
double localSum = 0.0;
for (i = omp_get_thread_num() * num_steps; i < num_steps; i++) {
x = (i + 0.5) * step;
localSum += 4.0 / (1.0 + x * x);
}
#pragma omp critical
sum += localSum;
};
printf("Execution time : %f\n", omp_get_wtime() - execution_time);
return step * sum;
}
int main() {
omp_set_num_threads(4);
printf("Result : %f\n", piCalculation());
}
@muatik
Copy link

muatik commented Apr 14, 2017

sum_execution_time += execution_time; this statement may cause raise condition. The sum operation should be atomic.

@feyyazesat
Copy link
Author

I used the mutex to sync sum_execution_time and sum shared variables with using #pragma omp critical directive. Could you check this again @muatik

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment