采用trap函数实现梯形积分的OpenMP并行程序 1) double Trap(double a, double b, int n, int thread_count) 2) 利用reduction保护临界区
时间: 2024-06-05 17:06:34 浏览: 104
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
double f(double x);
double Trap(double a, double b, int n, int thread_count);
int main(int argc, char* argv[]) {
double a = 0.0, b = 1.0, result = 0.0;
int n = 1000000, thread_count = 4;
#pragma omp parallel
#pragma omp master
thread_count = omp_get_num_threads();
result = Trap(a, b, n, thread_count);
printf("Result = %lf\n", result);
return 0;
}
double f(double x) {
return x * x;
}
double Trap(double a, double b, int n, int thread_count) {
double h = (b - a) / n;
double x = 0.0, sum = 0.0;
int i;
#pragma omp parallel for num_threads(thread_count) \
default(none) private(i, x) shared(a, h, n) \
reduction(+:sum)
for (i = 0; i < n; i++) {
x = a + i * h;
sum += 0.5 * (f(x) + f(x + h)) * h;
}
return sum;
}
阅读全文