将MPI_Scatter与 char* 数组一起使用

Using MPI_Scatter with char* array

本文关键字:数组 一起 char MPI Scatter      更新时间:2023-10-16

我是MPI编程的新手。所以我正在尝试使用 MPI_Scatter 将具有静态大小的 char* 数组分发到几个较小的 char* 数组中。但结果仅对 ID 0 正确,其余的具有垃圾值。你知道它有什么问题吗?

#include "mpi.h"
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
const static int ARRAY_SIZE = 130000;
using Lines = char[ARRAY_SIZE][16];
// To remove punctuations
struct letter_only: std::ctype<char> 
{
letter_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask> 
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc['A'], &rc['z'+1], std::ctype_base::alpha);
return &rc[0];
}
};

int main(int argc, char* argv[]) {
int processId;
int fillarraycount=0;
int num_processes;
// Setup MPI
MPI_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &processId);
MPI_Comm_size( MPI_COMM_WORLD, &num_processes);
Lines lines;
// Read the input file and put words into char array(lines)
if (processId == 0) {
std::ifstream file;
file.imbue(std::locale(std::locale(), new letter_only()));
file.open(argv[1]);
std::string workString;
int i = 0;
while(file >> workString){
memset(lines[i], '', 16);
memcpy(lines[i++], workString.c_str(), workString.length());
fillarraycount++;
}
}
int n =fillarraycount/num_processes;
char sublines[n][16];
MPI_Scatter(lines,n*16,MPI_CHAR,sublines,n*16,MPI_CHAR,0,MPI_COMM_WORLD);
std::cout<< processId<<" ";
for(int i=0;i<n;++i)
std::cout<<sublines[i]<<" ";
std::cout<<std::endl;
MPI_Finalize();
return 0;
}

我知道在那之后我也必须使用MPI_gather,但我对为什么 ID 0 上的子行产生了正确的数组块而其他 ID 产生了垃圾值感到困惑。

我尝试编译和测试程序
:模块加载 openmpi
mpic++ -std=c++11 try.cpp -o try mpirun -np 5 try try
.txt

哪里在尝试.txt:你好,
这是再次尝试文本文档这是尝试文本文档

是不是 si 是是哈哈

在 0 以外的排名上,n为 0,因为fillarraycount永远不会递增。如果fillarraycount是动态的,你必须首先向所有等级广播。