HuangJie
HuangJie

Reputation: 1530

MPI and its global variable

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();
}

Upvotes: 0

Views: 1519

Answers (1)

a3f
a3f

Reputation: 8657

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.

Upvotes: 1

Related Questions