0
votes

I tried to reproduce the question raised in this post. Below is my code. According to the answer, since every process runs independently, the global_variable should be 0 in process 1. However, process 1 also prints 1000. So in my understanding, the processes are spawned in MPI_Init, so if the global variables are defined before MPI_Init, the created processes will get the same value, right? Do I misunderstood that post?

#include <stdio.h>
#include <mpi.h>

static int global_variable;

main(int argc, char **argv)
{
    int ierr, num_procs, my_id;

    global_variable = 1000;

    ierr = MPI_Init(&argc, &argv);

    /* find out MY process ID, and how many processes were started. */

    ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

    if( my_id == 0 ) {
        printf("%d\n", global_variable);
    }
    else if( my_id == 1 ) {
        printf("%d\n", global_variable);
    }

    ierr = MPI_Finalize();
}
1
Just wondering, why are you storing all those ierr return values if you're not using them? - Kusalananda
There is a point in the comment by @Kusalananda. Moreover, the default error handler for MPI calls not related to file I/O terminates the entire job, therefore those MPI_... routines will either return MPI_SUCCESS or not return at all. Unless the MPI_ERRORS_RETURN error handler has been explicitly set, that is. - Hristo Iliev

1 Answers

1
votes

This is what independent means:

#include <stdio.h>
#include <mpi.h>

static int global_variable;

int main(int argc, char **argv)
{
    int ierr, num_procs, my_id;
    ierr = MPI_Init(&argc, &argv);

    ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

    if (my_id == 0) {
        global_variable = 1000;
    }
    MPI_Barrier(MPI_COMM_WORLD);
    printf("%d\n", global_variable);

    ierr = MPI_Finalize();
}

Here, only process 0 changes global_variable. In your example the global_variable = 1000; line isn't specific to any one process, and all processes will execute it.