采用Local_trap改写梯形积分的OpenMP并行程序: 1) double Local_trap(double a, double b, int n); 2) 利用critical和reduction两种方式保护临界区
时间: 2024-05-07 13:16:01 浏览: 140
1) 采用Local_trap改写梯形积分的OpenMP并行程序:
```c++
#include <iostream>
#include <omp.h>
double f(double x) {
return x * x;
}
double Local_trap(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for (int i = 1; i < n; i++) {
sum += f(a + i * h);
}
sum += (f(a) + f(b)) / 2.0;
sum *= h;
return sum;
}
int main() {
double a = 0.0, b = 1.0;
int n = 10000000;
double result_seq = Local_trap(a, b, n);
double result_par = Local_trap(a, b, n);
std::cout << "Sequential result: " << result_seq << std::endl;
std::cout << "Parallel result: " << result_par << std::endl;
return 0;
}
```
2) 利用critical和reduction两种方式保护临界区:
- 使用critical关键字:
```c++
#include <iostream>
#include <omp.h>
double f(double x) {
return x * x;
}
double Local_trap(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.0;
#pragma omp parallel
{
double local_sum = 0.0;
#pragma omp for
for (int i = 1; i < n; i++) {
local_sum += f(a + i * h);
}
#pragma omp critical
sum += local_sum;
}
sum += (f(a) + f(b)) / 2.0;
sum *= h;
return sum;
}
int main() {
double a = 0.0, b = 1.0;
int n = 10000000;
double result_seq = Local_trap(a, b, n);
double result_par = Local_trap(a, b, n);
std::cout << "Sequential result: " << result_seq << std::endl;
std::cout << "Parallel result: " << result_par << std::endl;
return 0;
}
```
- 使用reduction关键字:
```c++
#include <iostream>
#include <omp.h>
double f(double x) {
return x * x;
}
double Local_trap(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
for (int i = 1; i < n; i++) {
sum += f(a + i * h);
}
sum += (f(a) + f(b)) / 2.0;
sum *= h;
return sum;
}
int main() {
double a = 0.0, b = 1.0;
int n = 10000000;
double result_seq = Local_trap(a, b, n);
double result_par = Local_trap(a, b, n);
std::cout << "Sequential result: " << result_seq << std::endl;
std::cout << "Parallel result: " << result_par << std::endl;
return 0;
}
```
阅读全文