0

我正在探索 C++ 中的 MPI,我想并行创建 Mandelbrot 集的图片。我正在使用ppm格式。每个处理器构建自己的部分并将其发送回作为 MPI_CHAR 接收它的主进程。这是代码:

#include "mpi.h"
#include <iostream>
#include <string>
#include <fstream>
#include <complex>

using namespace std;

int mandelbrot(int x, int y, int width, int height, int max)  {
    complex<float> point((float) (y - height/2.0) * 4.0/width, (float) (x - width/2.0) * 4.0/width);
    complex<float> z(0, 0);
    unsigned int iteration = 0;

    while (abs(z) < 4 && iteration < max) {
           z = z * z + point;
           iteration++;
    }
    return iteration;
}

int main(int argc, char **argv) {
  int numprocs;
  int myid;
  int buff_size = 404270; // 200x200 
  char buff[buff_size];
  int i;

  MPI_Status stat;

  MPI_Init(&argc,&argv);
  MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD,&myid);

  int width = 200, height = 200, max_iter = 1000;

  if (myid == 0) {

    ofstream image("mandel.ppm");
    image << "P3\n" << width << " " << height << " 255\n";

    for(i=1; i < numprocs; i++) {
      MPI_Probe(i, 0, MPI_COMM_WORLD, &stat);
      int length;
      MPI_Get_count(&stat, MPI_CHAR, &length);
      MPI_Recv(buff, length, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
      image << buff;
    }

  } else {

    stringstream ss;
    // proc rank: 1, 2, ..., n
    int part = height/(numprocs-1), start = (myid - 1) * part, end = part * myid;
    printf("%d -> %d\n", start, end);

    for (int row = start; row < end; row++) {
        for (int col = 0; col < width; col++) {

            int iteration = mandelbrot(row, col, width, height, max_iter);

            if (row == start) ss << 255 << ' ' << 255 << ' ' << 255 << "\n";
            else if (iteration < max_iter) ss << iteration * 255 << ' ' << iteration * 20 << ' ' << iteration * 5 << "\n";
            else ss << 0 << ' ' << 0 << ' ' << 0 << "\n";
        }
    }

    printf("\n sizeof = %d\n", ss.str().length());
    MPI_Send(ss.str().c_str(), ss.str().length(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);
  }

  MPI_Finalize();

  return 0;  
}

代码编译:

$ mpic++ -std=c++0x mpi.mandel.cpp -o mpi.mandel

运行 3 个进程(进程主进程 + 进程等级 1 和 2)

$ mpirun -np 3 ./mpi.mandel

ppm使用 3、4 和 5 进程运行时的结果图片:

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

当超过 3 个进程尝试将 MPI_CHAR 元素发送到主进程时,似乎发送-接收的点对点通信正在混合结果。如何避免这种行为?

4

1 回答 1

0

它在创建buff与接收消息长度相同的缓冲区时起作用:

.
.
   for (int i=1; i < numprocs; i++) {
      MPI_Probe(i, 0, MPI_COMM_WORLD, &stat);
      int length;
      MPI_Get_count(&stat, MPI_CHAR, &length);
      printf("\nfrom %d <<-- %d (stat.source=%d) Receiving %d chars\n", myid, i, stat.MPI_SOURCE, length);
      char buff[length + 1];
      MPI_Recv(buff, length, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
      buff[length] = '\0';
      image << buff;
   }
.
.

int buff_size = 404270;因此,我们也不再需要一开始的声明char buff[buff_size];

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

于 2019-04-14T20:38:42.460 回答