Search code examples
c++visual-studio-2017openmp

simple openmp c++ problem when using for loop


This is a code for parallel compute Fibonacci sequence. I would like to know how it works during the Fibonacci series calculation. The calculation of the Fibonacci series requires the involvement of two previous values, how is it ensured in OpenMP that the two previous values must have been calculated? If they are not calculated then how does it work?

#include <omp.h>
#include <iostream>
using namespace std;
const int N = 20;
int main()
{
    int i, tid;
    int a[N];
    a[0] = 0;
    a[1] = 1;
    omp_set_num_threads(4);
#pragma omp parallel shared(a) private(i, tid)
    {

#pragma omp for
        for (i = 2; i < N; i++) {
            a[i] = a[i - 1] + a[i - 2];
            printf("i = %d, I am Thread %d\n", i, omp_get_thread_num());
        }
            
    }
    for (i = 0; i < N; i++)
        cout << a[i] << endl;
    return 0;
}

In addition to this, if I don't use a printf statement in the for loop, then this code runs correctly, but if I add the intermediate printf statement, the final calculation becomes enter image description here


Solution

  • Sorry, This algorithm cannot just be parallelized by applying OpenMP pragmas.

    As you already indicated in your question, the for i loop suffers from 'loop carried dependence': a[i-1] and a[i-2] need to be calculated before.

    OpenMP does not have the magic to do such a thing.

    Your printf() likely has a mutex inside, effectively killing the parallelization.