如何使用 MPI 程序从命令行读取参数

How do I read arguments from the command line with an MPI program?

本文关键字:命令行 读取 参数 程序 何使用 MPI      更新时间:2023-10-16

如何在C++中从命令行读取参数?

我目前有这个代码:

int data_size = 0;
std::cout << "Please enter an integer value: ";
std::cin >> data_size;
std::cout << "The value you entered is " << data_size;

主要:

int main(int argc, char** argv) {
        int data_size = 0;
        std::cout << "Please enter an integer value: ";
        std::cin >> data_size;
        std::cout << "The value you entered is " << data_size; 

    // initialise the MPI library
    MPI_Init(NULL, NULL);
    // determine the world size
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    // determine our rank in the world
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    std::cout << "rank " << world_rank << " size " << world_size << std::endl;
    if (world_rank == 0){
        coordinator(world_size);
    }
    else{
        participant(world_rank, world_size);
    }
    MPI_Finalize();
    return 0;
}

它可以工作,但它一直要求我输入整数值 4 次然后当我输入一个数字时,命令行会冻结。

这是我在命令行中得到的

C:UsersRolandDocumentsVisual Studio 2013ProjectsDistributedSystemsDebug>m
piexec -n 4 .DistributedSystems.exe
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value: 

对于 MPI 程序,用 std::cin 阅读东西不是一个好主意。我不知道你怎么能让它以这种方式工作,你只是不应该。

不过,以下是您的替代方案:

如果代码的输入足够小,可以作为命令行参数传递,请执行此操作。在您的示例中,您的输入代码块将更改为

// Do some error handling if needed, then
int data_size = std::atoi(argv[1]);

并开始像这样的工作

mpiexec -n 4 .DistributedSystems.exe k

k是您希望data_size成为的数字。

如果您应该达到输入量较大的程度以方便使用,请将其写入文件中并按上述方式传递输入文件名。然后,每个进程都可以以自己的std::ifstream打开该文件并从那里读取数据。

根据 Rob Latham 的说法,这项工作是一种特定于实现的行为。但是,如果您的系统使用命令行界面,您通常可以期望它起作用。