c++ - 如何使用 MPI 程序从命令行读取参数?

标签 c++ command-line mpi

如何在 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:\Users\Roland\Documents\Visual Studio 2013\Projects\DistributedSystems\Debug>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 ,此工作是特定于实现的行为。但是,如果您的系统使用命令行界面,您通常可以期望它能正常工作。

关于c++ - 如何使用 MPI 程序从命令行读取参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952406/

相关文章:

windows - 如何创建可视化 SVN 存储库并获取该 URL

command-line - 通过 Outlook 从命令行发送电子邮件而无需单击发送

c++ - 自动类型的 MPI 广播变量

c - MPI_Send 或 MPI_Recv 的限制?

c++ - 如何将 boost asio 接受器限制为本地主机和/或本地网络?

c++ - 如何解释 C++ 中的二进制数据?

c# - 将对象从 C# 传递到 C++ 得到 "cannot use this indirection"?

ubuntu - 如何使用 S3QL 在 aws s3 中列出对象

c - 如何计算百分比?

c++ - 状态检查总是一件有效的事情吗?