0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so, in every routine i must use MPI_Comm_rank and print in only 1 rank, but i need call MPI_Init in every routine too?
you shouldn't need to call MPI_Init in outside functions--just in your main
0

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

Comments

0

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. 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.