我是 C 初学者(在 C++ 方面经验很少),我对用户输入变量值有疑问。我用 C编写MPI_Scatter和MPI_Gather编程,它将计算每个节点上输入整数的总数。
问题是:如果我定义变量输入(见下面的代码),input=5;因为它将计算所有4节点的总和(210)。如果我为 设置输入scanf,结果将仅为15. 变量似乎改变了它的值。你能帮我吗?代码:
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define MASTER 0
int main(int argc, char** argv){
int id, nproc;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
MPI_Comm_rank(MPI_COMM_WOLRD, &id);
MPI_Status status;
int input=0; // <- problematic variable
int nodeValue=0;
int size;
int *array;
if(id == MASTER){
printf("How many elements per node? ");
scanf("%d", &input);
nodeValue = input;
}
MPI_Barrier(MPI_COMM_WORLD);
if(id == MASTER){
size = input * nproc;
array = malloc(sizeof(int)*size);
...
}
}
Run Code Online (Sandbox Code Playgroud)
您的查询类似于以下堆栈溢出问题:在 MPI 中访问多进程 scanf 仅接受一次输入并将垃圾值分配给其他进程?
给出的选项为:请从文件中读取输入。
这是从文件中读取的示例代码:
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int myid, nprocs;
int *array;
int size, i;
FILE *fp;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
if(myid ==0)
{
fp = fopen("test", "r");
fscanf(fp, "%d", &size);
}
/* MPI_Bcast(void *buffer,
int count,
MPI_Datatype datatype,
int root,
MPI_Comm comm) */
MPI_Bcast(&size,1, MPI_INT, 0, MPI_COMM_WORLD);
array = (int *) malloc(size* sizeof(int));
if(myid ==0)
{
for(i = 0; i < size; i++)
{
fscanf(fp, "%d", &array[i]);
}
}
MPI_Bcast(array, size, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Finalize();
}
Run Code Online (Sandbox Code Playgroud)
这是包含一些示例的链接:访问https://docs.loni.org/wiki/c_mpi_examples
如果确实需要用户输入:我们有的选项是
1)从命令行参数或文件中读取(编写代码以输入到该文件 - 尽管这是一个冗长的方法)
2) 在 MPI_Init 之后,STDIN 不会按预期工作。尝试将您的 scanf 语句放在 MPI_Init 之前。
修改后的代码:请试试这个:
int id, nproc;
MPI_Status status;
int input=0; // <- problematic variable
int nodeValue=0;
int size;
int *array;
if(id == MASTER){
printf("How many elements per node? ");
scanf("%d", &input);
nodeValue = input;
}
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
MPI_Comm_rank(MPI_COMM_WOLRD, &id);
Run Code Online (Sandbox Code Playgroud)