c - 调试 C 语言并行程序

标签 c parallel-processing openmp fibonacci

我在 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/

相关文章:

c - 指针。这是好的编程风格吗?

c# - C#并行ForEach保持值

c++ - 编译器优化消除了错误共享的影响。如何?

c++ - 互斥实现可以互换吗(独立于线程实现)

c - omp_set_num_threads 我应该每次都使用它还是可以设置一次?

c - 为什么 char 变量中允许 4 个字符?

C函数后链接节点丢失

c - #pragma pack(2)的含义

parallel-processing - F#如何并行做List.map

python - 在 Python 中并行化 for 循环以加快算法速度