Sections和OpenMP代码有时会挂起

O.S*_*aya 4 c c++ openmp

我有使用OpenMP和C++的代码.代码正确执行但有时会挂起.我正在使用部分.你能告诉我这是什么问题吗?我尝试了几件事,但没有一件工作,比如将变量从私有变为共享.

#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); 

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

mas*_*tov 6

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

你在函数中有一个障碍,print_results它只由碰巧分配给两个部分之一的线程执行.所有额外的线程都有一个障碍.不等数量的障碍阻碍了您的计划.

确保仅在您知道所有线程将执行它的位置放置障碍.