gpt4 book ai didi

c++ - 部分和 OpenMP 代码有时会挂起

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:11 25 4
gpt4 key购买 nike

我有这段代码使用 OpenMP 和 C++。代码正确执行但有时会挂起。我正在使用部分。你能告诉我问题是什么吗?我尝试了几件事,但都没有奏效,比如将变量从私有(private)更改为共享。

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N 50

//gcc -fopenmp -o e3 e3.c
int main (int argc, char *argv[])
{
int i, nthreads, tid, section;
float a[N], b[N], c[N];
void print_results(float array[N], int tid, int section);

/* Some initializations */
for (i=0; i<N; i++)
a[i] = b[i] = i * 1.0;

#pragma omp parallel private(c,i,tid,section)
{
tid = omp_get_thread_num(); //FIXME: how to get the thread id?
if (tid == 0)
{
nthreads = omp_get_num_threads(); //FIXME: how to get the number of threads?
printf("Number of threads = %d\n", nthreads);
}

/*** Use barriers for clean output ***/
#pragma omp barrier
printf("Thread %d starting...\n",tid);
#pragma omp barrier

#pragma omp sections nowait
{
#pragma omp section
{
section = 1;
for (i=0; i<N; i++)
c[i] = a[i] * b[i];
print_results(c, tid, section);
}

#pragma omp section
{
section = 2;
for (i=0; i<N; i++)
c[i] = a[i] + b[i];
print_results(c, tid, section);
}

} /* end of sections */

/*** Use barrier for clean output ***/
#pragma omp barrier
printf("Thread %d exiting...\n",tid);

} /* end of parallel section */

printf("I am out of parallel scope\n");
return 0;
}



void print_results(float array[N], int tid, int section)
{
int i,j;

j = 1;
/*** use critical for clean output ***/
#pragma omp critical
{
printf("\nThread %d did section %d. The results are:\n", tid, section);
for (i=0; i<N; i++) {
printf("%e ",array[i]);
j++;
if (j == 6) {
printf("\n");
j = 1;
}
}
printf("\n");
} /*** end of critical ***/

#pragma omp barrier
printf("Thread %d done and synchronized.\n", tid);

}

谢谢!

最佳答案

屏障用于同步所有线程。所有线程都将被阻塞,直到所有线程都到达屏障。因此,为了让您的程序终止,所有线程在其生命周期中都必须达到相同数量的障碍。如果一个线程比其他线程有更多的屏障,则该线程永远无法通过其额外屏障,因为它将等待其他线程 - 其他线程永远不会到达那里,因为它们没有额外屏障。

您在函数 print_results 中设置了屏障,它仅由恰好分配到两个部分之一的线程执行。所有额外的线程都少了一个障碍。不等数量的障碍阻碍了您的程序。

确保只在您知道所有线程都会执行它的地方放置障碍。

关于c++ - 部分和 OpenMP 代码有时会挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com