Search code examples
cmultithreadingtaskopenmp

OpenMP fibonacci function and use of firstprivate


Why is firstprivate used in the below code snippet from here? Removing firstprivate does not seem to have any effect on the final result. My understanding of firstprivate is that the value of the variable n will be initialized by whichever thread touched the variable n first, and then n after initialization is private to the thread in the task (parallel??) region. By default, variables in a parallel region are shared, but since the value of n is never modified by any other threads, there doesn't seem to be any reason to make n private to a thread.

#include <stdio.h>
#include <omp.h>
int fib(int n)
{
  int i, j;
  if (n<2)
    return n;
  else
    {
       // removing `firstprivate(n)` does not affect correctness
       #pragma omp task shared(i) firstprivate(n)
       i=fib(n-1);

       // removing `firstprivate(n)` does not affect correctness
       #pragma omp task shared(j) firstprivate(n)
       j=fib(n-2);

       #pragma omp taskwait
       return i+j;
    }
}

int main()
{
  int n = 10;

  omp_set_dynamic(0);
  omp_set_num_threads(4);

  #pragma omp parallel shared(n)
  {
    #pragma omp single
    printf ("fib(%d) = %d\n", n, fib(n));
  }
}

Solution

  • Data in tasks is firstprivate by default. That's mostly because you don't know when a task will be executed, so having data be shared may give strange results in many cases. I guess that the committee wanted you to spell it out if you really wanted data to be shared.

    Btw, the point of firstprivate is not so much that it's private, but that it is immediately copied when the task is created. Again: if it was shared the value may have been very different when the task is executed from when it was created.