Fabricio
Fabricio

Reputation: 343

MPI 2x printing

I'm studying a bit of MPI, and decided to do a test by making a program that calls objects, eg main.c -> main program, function.c -> any function

function.c that will only use the MPI. compiling I as follows:

gcc-c main.c

to create main.o, mpicc-c to create function.c function.o, of course I create the file function.h too.

I compile with mpicc-o program main.o function.o

Here is main.c

#include <stdio.h>
#include "function.h"

void main(int argc, char *argv[])
{
  printf("Hello\n");
  function();
  printf("Bye\n");
}

just function has the MPI code, but when I'm running the program mpiexe -np 2 I get

Hello
Hello
----- function job here -----
Bye
Bye

But I wanted it to be

Hello
------ function job -----
Bye

What can I do?

Upvotes: 0

Views: 193

Answers (3)

prathmesh.kallurkar
prathmesh.kallurkar

Reputation: 5686

I generally prefer this method for printing data. It involves barriers. So you must be careful while using it.

if(1)
do
  for(i = 0 to num_threads)
  do
     if(i==my_rank)
     do
       do_printf
     done

      ******* barrier ********
  end for
done

If the set of threads printing the value does not include all threads, just add the relevant threads to barrier.

Another method is for every thread to write its output in a dedicated file. This way :

  1. you don't have to access a barrier
  2. you do not lose printfs of any thread
  3. you output is explicit. so there is no cluttering while debugging programs.

Code :

sprintf(my_op_file_str, "output%d", myThreadID);
close(1)
open(my_op_file_str)

Now use printf's anywhere you may like.

Upvotes: 0

Jonathan Fretheim
Jonathan Fretheim

Reputation: 902

Your whole program is run on both of the two processors you set with the -np 2. A common way to prevent duplicates of printouts, final results, etc., is have one thread do those things just by checking the thread id first. Like:

int id;
MPI_Comm_rank(MPI_COMM_WORLD, &id);
if (id == 0) {
  printf("only process %d does this one\n", id);
}

printf("hello from process %d\n", id);  // all processes do this one

When starting out in MPI I found it helpful to print out those id numbers along with whatever partial results or data each thread was dealing with. Helped me make more sense out of what was happening.

Upvotes: 1

Elalfer
Elalfer

Reputation: 5338

Basically mpirun -np 2 starts 2 identical processes and you have to use MPI_Comm_rank function to check process rank.

Here is a quick snippet:

int main(int argc, char **argv)
{
  int myrank;
  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  if (myrank == 0) {
    printf("Hello\n");
    function();
    MPI_Barrier(MPI_COMM_WORLD);
    printf("Done\n");
  } else {
    function();
    MPI_Barrier(MPI_COMM_WORLD);
  }
  MPI_Finalize();
  return 0;
}

Upvotes: 0

Related Questions