0

I have the following program in OPen MP (C).

It sometimes gives 0 or 3 as the fibonnaci number or crashes giving segmentation fault.

#include <stdlib.h>
#include <stdio.h>
#include <omp.h>

static int fib(int);

int main(){
 int nthreads, tid;
 int n =8;
 #pragma omp parallel num_threads(4) private(tid)

{
 #pragma omp single

{
 tid = omp_get_thread_num();
 printf("Hello world from (%d)\n", tid);
 printf("Fib(%d) = %d by %d\n", n, fib(n), tid);

}
 } // all threads join master thread and terminates
 }
static int fib(int n){
 int i, j, id;
 if(n < 2)
 return n;
 #pragma omp task shared (i) private (id)

{

i = fib(n-1);

}
 #pragma omp task shared (j) private (id)
{
 j = fib(n-2);

}

 return (i+j); 
}

What is wrong with the program ?

The output is like:

Hello world from (3)

Fib(8) = 3 by 3

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
ferrer
  • 135
  • 3
  • 10
  • 1
    So you've heard a cure from Selçuk Cihan. Did it work? I'd really love to hear what the performance numbers are; Fib(n) implemented this way is kind of the hardest thing on earth to parallelize well. For comparison numbers, see http://stackoverflow.com/q/5086040/120163 – Ira Baxter Jan 25 '16 at 04:08

1 Answers1

1

You need to have a taskwait as in #pragma omp taskwait right before returning (i+j). Otherwise it will return before the numbers are fully computed, without waiting the other tasks.

Selçuk Cihan
  • 1,979
  • 2
  • 17
  • 30