OpenMP 共享内存编程

梯形积分法

菜包的总结

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

知识点

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

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
运行及结果
> 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 !

你可能感兴趣的:(OpenMP 共享内存编程)