我是MPI編程的新手。所以我正在嘗試使用MPI_Scatter將具有靜態大小的char *數組分配到char *數組的較小塊中。但是結果只對ID 0正確,其餘的都有垃圾值。你知道它有什麼問題嗎?用char *數組使用MPI_Scatter
#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], '\0', 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嘗試
的mpirun -np 5試try.txt
其中try.txt:
您好,這是try文本文檔
又是這種嘗試的文本文檔
是被NOTIS Si是是是是哈哈
這可能不會幫助,我記得遇到類似的問題,並通過使用指針和'malloc'而不是數組來解決它。 ('char [x] [y] - > char * sublines = malloc(sizeof(char)* x * y)')。唯一其他的事情是確保num_processes在編譯時被定義(否則像這樣聲明數組是無效的,不可能知道要分配多少內存),並最終完成檢查:你做了分散,**你是否收集你的結果回來**?你必須[分散和收集](http://mpitutorial.com/tutorials/mpi-scatter-gather-and-allgather/);) – sjm324
請提供[mcve]。 – Zulan