【问题标题】:Writing file for each process of MPI为MPI的每个进程写入文件
【发布时间】:2021-03-16 15:56:40
【问题描述】:

我已经编写了这部分代码,以便为每个等级创建一个文件并查看其内容。我的问题是如何扩展此代码以适用于任意大小。在这里,因为我使用 4 个内核运行;我已经知道我的大小,所以我用 4 个 if 条件编写了我的代码,我认为应该有更好的方法来处理更多的进程。

string local_string = to_string(rank) + base;
ofstream output{ local_string };
if (local_string == "0.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl; 
    }
}

if (local_string == "1.txt") {
    for (int i = 0; i < N;i++) {
        output <<data[i] << endl;
    }
}

if (local_string == "2.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl;
    }
}

if (local_string == "3.txt") {
    for (int i = 0; i < N;i++) {
        output << data[i] << endl;
    }
}

【问题讨论】:

    标签: c++ parallel-processing output mpi hpc


    【解决方案1】:

    由于您正在并行运行多个进程,因此您实际上不需要指定条件:

    string local_string = to_string(rank) + base;
    read the file with the name local_string
    and print the content of the file to the output
    

    如果出于调试目的,您可能想要添加一个条件,以便您只打印具有特定等级的进程文件:

        if(rank == rank_to_print_the_file){
           string local_string = to_string(rank) + base;
           read the file with the name local_string
           and print the content of the file to the output
       }
    

    【讨论】:

      【解决方案2】:

      在写入文件之前使用MPI_Barrier 将消除我们对每个进程的条件的想法

      【讨论】:

      • 你需要什么屏障?
      • 因为我在开始写入文件之前使用了Barrier,如果条件和创建的文件相同,我就删除了。事实上,它们的顺序是我想要的:比如 0.txt 包含排名 0 的数据,而 1.txt 包含排名 1 的数据
      • 你尝试过没有障碍和条件的写作吗?
      • 哦,这很奇怪。既然您提到我尝试评论 MPI_Barrier 并且没关系。但是,我记得没有Barrier,排序就有问题
      • 您可以添加只是为了“安全”,但我认为您不需要。
      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2014-06-15
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多