让奴隶等待主人的MPI_Bcast

时间:2013-01-22 10:43:53

标签: c parallel-processing mpi

我正在尝试使用MPI和C语言编写一个实现高斯消除管道版本的并行程序...

但是我在代码实现的早期遇到了一些困难......

我使用根进程从文本文件中读取数据矩阵...这个过程给出了这个矩阵的大小,我将它的大小广播到所有其他进程,以便它们在内存中分配它...但是,从进程正试图在从根目录广播之前分配它... 我该如何让他们等待?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

int CalcInd(int i, int j, int dimL)
{
  return i*dimL +j;
}

int main (int argc, char **argv)
{
  FILE *fin, *fout;
  char fA[] = "Matrix.txt";

  int rank, size, i, ii, j, k, m, n, picked, tmp, total;
  int  counter=0, elements=0;
  int * RightNeigbhor, * LeftNeigbhor, * loc;

  float f, magnitude, t;
  float * A, * x;

  MPI_Status status;
  MPI_Request request;

  // MPI initialization
  MPI_Init(&argc, &argv);  
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  MPI_Barrier(MPI_COMM_WORLD);

  if(rank == 0)
  {
    // Defenição dos processos vizinhos pelo master
    RightNeigbhor = (int *)calloc(size,sizeof(int));
    if(RightNeigbhor==NULL)
      {printf("!!! Could not allocate memory !!!\n"); exit(-1);}
    LeftNeigbhor = (int *)calloc(size,sizeof(int));
    if(RightNeigbhor==NULL)
      {printf("!!! Could not allocate memory !!!\n"); exit(-1);}

    for(i = 0; i < size; i++ )
    {
      RightNeigbhor[i] = (rank + 1) % size;
      LeftNeigbhor[i] = (rank - 1) % size;
    }
    // Broadcast os processos vizinhos para todos os processos
    MPI_Bcast ( RightNeigbhor, size, MPI_INTEGER, rank, MPI_COMM_WORLD );
    MPI_Bcast ( LeftNeigbhor, size, MPI_INTEGER, rank, MPI_COMM_WORLD );

    // Leitura da matriz A pelo master
    fin = fopen ( fA, "r" ); 
    if (fin == NULL){ printf("!!! FILE NOT FOUND !!!"); exit(-1); }
    while( !feof(fin))
    {
      fscanf (fin, "%f", &f);
      elements++;
    }
    rewind(fin);
    f = 0;

    while( !feof(fin))
    {
      if(fgetc(fin) == '\n')
      {
    counter++;
      }
    }
    rewind(fin);

    n = counter;
    m = (elements-1) / counter;

   total = n*m;   

   MPI_Bcast ( &total, 1, MPI_INT, rank, MPI_COMM_WORLD );
   MPI_Bcast ( &n, 1, MPI_INT, rank, MPI_COMM_WORLD );

  }

  // Alocação de variaveis
  A = (float *)calloc(total,sizeof(float));
  if(A==NULL){printf("!!! Could not allocate memory !!!\n"); exit(-1);}
  loc = (int *)calloc(n,sizeof(int*));
  if(loc==NULL){printf("!!! Could not allocate memory !!!\n"); exit(-1);}

// AND IT GOES ON AND ON

1 个答案:

答案 0 :(得分:4)

rank == 0块中的所有内容仅在流程0中运行。而流程rank == 1 ... n只是跳过该块。因此,您必须将MPI_Bcast来电置于MPI_Comm comm此处MPI_COMM_WORLD所有流程可见的环境中。当进程1 ... n跳过所有初始化并在进程0到达之前跳转到广播,它们将等到bcast发生。