Reputation: 97
I am a beginner in C (have few experiences in C++) and I have a problem with user input variable value. I wrote MPI_Scatter
and MPI_Gather
program in C which would calculate the total sum of number of inputted integers on every node.
The problem is: if I define variable input (see code below) as input=5;
it will calculate the whole sum for all 4
nodes (210
). If I set the input for scanf
, a result will be only 15
. It seems that the variable change its value. Can you help me please?
Code:
#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);
...
}
}
Upvotes: 2
Views: 3285
Reputation: 179
Your query is similar to below stack overflow issue: Visit In MPI for multiple process scanf taking input only once and assign garbage values to other?
Option given as: please read input from file.
Here is the sample code to read from file:
#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();
}
Here is the link has some examples: Visit https://docs.loni.org/wiki/c_mpi_examples
If it is really needs an user input: option we have are
1) Read from command line arguments or from file (write a code to input to that file - though it is a lengthy approach)
2) STDIN won't work as expected after MPI_Init. Try to put your scanf statement before MPI_Init.
Modified code: Please try this:
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);
Upvotes: 5