如何使用OpenMP正确并行化此程序

时间:2015-12-02 17:39:49

标签: c multithreading parallel-processing openmp interpolation

我正在使用OpenMP学习并行化概念。所以我有关于插值的程序,我试着并行化这个程序,但我想知道这是否是正确的形式。 这是该计划:

功能'主要'通过生成一些测试点,然后调用' polint'来演示多项式插值函数。用一个  两个测试点之间的x值。

多项式插值 该程序演示了执行多项式的函数 插值。该功能取自" Numerical Recipes 在C",第二版,William H. Press,Saul A. Teukolsky, William T. Vetterling和Brian P. Flannery。

#include<math.h> 
#include<stdlib.h> 
#include<stdio.h>
#include<openmp.h>
#define N 20 
#define X 14.5
int main (intargc, char *argv[]) {
double x, y, dy;
double *xa, *ya;
int i;
xa = vector (1, N); ya = vector (1, N);
/* Initialize xa's and ya's */
for (i = 1; i<= N; i++) {
    init (i, &xa[i], &ya[i]);
    printf ("f(%4.2f) = %13.11f\n", xa[i], ya[i]);
}
/* Interpolate polynomial at X */
polint (xa, ya, N, X, &y, &dy);
printf ("\nf(%6.3f) = %13.11f with error bound %13.11f\n", X, y, fabs(dy));
free_vector (xa, 1, N); free_vector (ya, 1, N); return 0;

}

功能&#39;签署&#39;和&#39; init&#39;用于初始化保存函数已知值的x和y向量。

int sign (int j)
{
    if (j % 2 == 0) return 1;
    else return -1;
}
void init(inti, double *x, double *y) {
    // int j;
    *x = (double) i;
    *y = sin(i);
}

功能&#39; polint&#39;执行多项式插值

void polint (double xa[], double ya[], int n, double x, double *y,     double *dy) {
inti, m, ns=1;
doubleden,dif,dift,ho,hp,w;
double *c, *d;
dif = fabs(x-xa[1]); c = vector(1,n);
d = vector(1,n);
#pragma omp parallel
{
    #pragma omp for
    for (i=1; i<= n; i++)
    {
        #pragma section
        dift = fabs (x - xa[i]);
        #pragma omp simple
        {
            if (dift<dif)
            {
                ns = i;
                dif = dift;
            }
        }
        c[i] = ya[i];
        d[i] = ya[i];
    }
}
*y = ya[ns--];
#pragma omp paralel
{
    #pragma for reduction(/: den)
    shared(m, n)
    for (m = 1; m < n; m++)
    {
        for (i = 1; i<= n-m; i++)
        {
            ho = xa[i] - x;
            hp = xa[i+m] - x;
            w = c[i+1] - d[i]; den = ho - hp;
            den = w / den;
            d[i] = hp * den;
            c[i] = ho * den;
        }
        #pragma omp section
        *y += (*dy=(2*ns < (n-m) ? c[ns+1] : d[ns--]));
    }
    #pragma omp section
    free_vector (d, 1, n); free_vector (c, 1, n); }
  }

功能&#39; free_vector&#39;用于释放分配了函数&#39; vector&#39;

的内存
void free_vector(double *v, long nl, long nh) {
    free ((char *) (v+nl-1));
}

功能&#39;矢量&#39;用于分配带有下标范围v [nl..nh]

的向量
double *vector (long nl, long nh) {
    double *v;
    v = (double *) malloc(((nh-nl+2)*sizeof(double))); return v-nl+1;
}

0 个答案:

没有答案