Skip to content

Instantly share code, notes, and snippets.

@mcanvar
Created June 7, 2016 11:27
Show Gist options
  • Save mcanvar/a8d94054c976251af3a61c38e63560dc to your computer and use it in GitHub Desktop.
Save mcanvar/a8d94054c976251af3a61c38e63560dc to your computer and use it in GitHub Desktop.
Parallel programming final exam 3rd question. C parallel program that calculate trapezoidal area via OpenMP.
/*
Paralel Programlama Final Soruları
Soru 3) Argüman olarak n sayısını alan ve geriye trapezoidal alanı döndüren C programını OPENMP ile yazınız.
n in tek olduğu durumlar göz önüne alınmalıdır.
Compile: gcc -g -Wall -o calculateTrapAreaOpenMP calculateTrapAreaOpenMP.c -lm -lpthread
Run: ./calculateTrapAreaOpenMP <number of threads> <n>
[email protected]
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#define A_POINT 0.0
#define B_POINT 0.8
double f(double x) {
return 0.2 + 25 * x + -200 * pow(x, 2) + 675 * pow(x, 3) - 900 * pow(x, 4) + 400 * pow(x, 5);
}
void Trap(int n, double* global_result_p) {
double h, x, my_result, tempRemainder;
double local_a, local_b;
int i, local_n;
int my_rank = omp_get_thread_num();
int thread_count = omp_get_num_threads();
h = (B_POINT - A_POINT) / n;
if (n % thread_count == 0) {
local_n = n / thread_count;
local_a = A_POINT + my_rank*local_n*h;
local_b = local_a + local_n*h;
}
else {
tempRemainder = n % thread_count;
local_n = (n - tempRemainder) / thread_count;
local_a = A_POINT + my_rank*local_n*h;
if (my_rank == thread_count - 1) {
local_b = local_a + local_n*h + tempRemainder;
}
else {
local_b = local_a + local_n*h;
}
}
my_result = (f(local_a) + f(local_b)) / 2.0;
for (i = 1; i <= local_n - 1; i++) {
x = local_a + i*h;
my_result += f(x);
}
my_result = my_result*h;
# pragma omp critical
*global_result_p += my_result;
}
int main(int argc, char* argv[]) {
int n = 10;
int thread_count = 10;
double global_result = 0.0;
//sınav için gerekli: değerleri konsoldan alıyoruz.
//thread_count = strtol(argv[1], NULL, 10);
//n = strtoll(argv[2], NULL, 10);
# pragma omp parallel num_threads(thread_count)
Trap(n, &global_result);
printf("%lf\n", global_result);
system("PAUSE");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment