欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用共享任务结构并行计算π的OpenMP代码段

程序员文章站 2022-07-12 20:03:31
...
#include "stdafx.h"
#include <cstdio>
#include <iostream>
#include <omp.h>
using namespace std;
static long num_steps = 100000;
#define NUM_THREADS 2

void main(){
    int i;
    double x, pi, sum[NUM_THREADS];
    double step = 1.0 / num_steps;
    omp_set_num_threads(NUM_THREADS);
# pragma omp parallel private(i,x) shared(sum)
    {
        int id = omp_get_thread_num();
        sum[id] = 0;
# pragma omp for
        for (i = 0; i < num_steps; i++)
        {
            x = (i + 0.5)*step;
            sum[id] += 4.0 / (1.0 + x * x);
        }
    }
    for (i = 0, pi = 0; i < NUM_THREADS; i++)
        pi += sum[i] * step;
    printf("%f\n",pi);
}
相关标签: OpenMP 并行计算