我在 OPen MP (C) 中有以下程序。
它有时会给出 0 或 3 作为斐波那契数,或者崩溃导致段错误。
#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);
}
程序出了什么问题?
输出如下:
Hello world from (3)
Fib(8) = 3 by 3
最佳答案
在返回(i+j)
之前,您需要像#pragma omp taskwait
一样进行任务等待。否则它将在数字完全计算之前返回,而不等待其他任务。
关于c - 调试 C 语言并行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981408/