OpenMP 共享内存编程

梯形积分法

菜包的总结

首次撸OpenMP示例程序,==关键问题在于C语言的语法及基础知识的不足;
其次对于OpenMP编程模型的掌握还不熟练;

知识点

  1. scanf()输入%lf-->double;%f-->float;%d-->int; …
    其中后半部分是&a,不能写变量名称;
  2. openMP 基本块:
    -并行部分: # pragma omp parallel ...;
    -互斥部分: # pragma omp critical...;
源码:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void Trap(double a,double b,int n,double* res);
double f(double d);

int main(int argc,char* argv[]){
  int thread_count = strtol(argv[1],NULL,10);
  int n;
  double a,b;
  double res=0.0;

  printf("Please input a, b and n\n");
  scanf("%lf,%lf,%d",&a,&b,&n);
  printf("a is: %f, b is: %f, n is %d \n ", a,b,n); 

# pragma omp parallel num_threads(thread_count)
  Trap(a,b,n,&res);

  printf("Result is %lf !\n",res);
  return 0;
}

void Trap(double a,double b,int n,double* res){
  double h,x,my_res;
  double local_a,local_b;
  int i,local_n;
  int rank = omp_get_thread_num();
  int thread_count = omp_get_num_threads();

  h=(b-a)/n;
  local_n = n/thread_count;
  local_a = a+h*rank*local_n;
  local_b = local_a+local_n*h;
  my_res = (f(local_a)+f(local_b))/2.0;

  for(i=1;i<local_n;i++){
    x = local_a+i*h;
    my_res+=f(x);
  }
  my_res = my_res*h;

# pragma omp critical
  *res+=my_res;
}

double f(double d){
  return d*d;
}
运行及结果
> gcc -g -Wall -fopenmp -o Tixing Tixing.c  
> ./Tixing 5 
Please input a, b and n
0.0,10.0,1000
a is: 0.000000, b is: 10.000000, n is 1000 
 Result is 333.333500 !
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容