簡體   English   中英

Sections和OpenMP代碼有時會掛起

[英]Sections and OpenMP code hangs sometimes

我有使用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); 

}

謝謝!

障礙用於同步所有線程。 所有線程都將被阻塞,直到所有線程都到達屏障。 因此,為了使您的程序終止,所有線程在其生命中必須達到相同數量的障礙。 如果一個線程比其他線程有更多的障礙,那么該線程永遠不能通過它的額外障礙,因為它將等待其他線程 - 這將永遠不會到達那里,因為它們沒有那個額外的障礙。

函數print_results有一個障礙,它只由碰巧分配給兩個部分之一的線程執行。 所有額外的線程都有一個障礙。 不等數量的障礙阻礙了您的計划。

確保僅在您知道所有線程將執行它的位置放置障礙。

雖然我找到了“解決方法”,但我還不確定發生了什么。

您只使用兩個部分,但允許兩個以上的線程。 如果通過更改將線程數限制為2

#pragma omp parallel private(c,i,tid,section)

#pragma omp parallel private(c,i,tid,section) num_threads(2),

該計划將終止。 (我無法重現錯誤。)

如果將線程數設置為3,程序將始終掛起。 (至少它從未終止。我試過了大約20次。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM