簡體   English   中英

在MPI中使用char []發送結構

[英]Send struct with char[] in MPI

我正在嘗試將一些數據從工作人員發送到C ++中的MPI程序中的主服務器(排名為0)。 目標是傳遞2個字符串和一個整數。 為此,我創建了一個結構。

結構

它稱為單詞 ,定義如下:

struct word
{
    char word_name[str_size];
    char url[str_size];
    int counter;
};

/* Some important variables to the question */

MPI_Datatype mpi_word_type;
const int str_size = 200;

以前,我是通過char *嘗試此操作的,但是它不起作用,因為進程沒有共享相同的內存空間。

現在,如果將變量從char[]更改為簡單的char並嘗試使用示例,則可以發送該結構。 如上所述,我無法擺脫分段錯誤。

發送零件-工人

首先創建並填充示例結構,然后首先發送結構的大小,然后發送結構本身。 像這樣:

word word_col;
std::string tmp = "somename";
strcpy(word_col.word_name, tmp.c_str());

std::string tmp2 = "someurl";
strcpy(word_col.url, tmp2.c_str());

word_col.counter = 10;

int size = sizeof(word_col);
MPI::COMM_WORLD.Send(&size, 1, MPI::INT, 0, 1);
MPI::COMM_WORLD.Send(&word_col, size, mpi_word_type, 0, 1);

接收部分-主

const int nitems = 3;
int blocklengths[3] = { str_size, str_size, 1 };
MPI_Datatype types[3] = { MPI::CHAR, MPI::CHAR, MPI::INT };
MPI_Aint offsets[3];

offsets[0] = (MPI_Aint) offsetof(struct word, word_name);
offsets[1] = (MPI_Aint) offsetof(struct word, url);
offsets[2] = (MPI_Aint) offsetof(struct word, counter);

MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_word_type);
MPI_Type_commit(&mpi_word_type);

...

for(...)
{
    word word_col;
    int size;

    MPI::COMM_WORLD.Recv(&size, 1, MPI::INT, MPI::ANY_TAG, 1, status);
    MPI::COMM_WORLD.Recv(&word_col, size, mpi_word_type, MPI::ANY_TAG, 1, status);
}

我已經為這個問題苦苦掙扎了好幾個小時,並且已經看到了許多示例和有關此問題的另一個問題,但是我無法弄清楚這是什么問題。

這是錯誤的編程。 您有未分配和未初始化的指針,並且您正在嘗試將數據推送到該指針。 您有兩個選擇:將結構定義為:

const int str_size = 200;
struct word
{
    char word_name[str_size]; // fixed sized char array
    char url[str_size]; // fixed sized char array
    int counter;
};

要么,

const int str_size = 200;
struct word
{
    char *word_name; /
    char *url;
    int counter;
    Word() {
      word_name = new char[str_size];
      url = new char[str_size];
    }
    ~Word() {
      delete [] word_name;
      delete [] url;
    }
};

這個想法是您需要為這些變量分配內存,此外,在接收時,您已經使用:

MPI::COMM_WORLD.Recv(&word_col, size, mpi_word_type, MPI::ANY_TAG, 1, status);

它不應該像下面嗎?

MPI::COMM_WORLD.Recv(&word_col, sizeof(word_col), mpi_word_type, MPI::ANY_TAG, 1, status);

暫無
暫無

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

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