FifthArrow
FifthArrow

Reputation: 185

How to determine if an MPI communicator is valid?

In my program, I have wrapped up some MPI communicators in to a data structure. Unfortunately, sometimes the destructor of an object of this type might get called before it has been initialized. In my destructor, I of course call MPI_Comm_Free. But if this is called on an invalid communicator the code crashes.

I've been looking through the MPI standard, but I can't find a function to test if a communicator is valid. I also assume I can't use MPI_Comm_set_errhandler to try and catch the free exception because there isn't a valid communicator to set the handler of. I could maintain a flag value of my own saying if the communicator is valid, but I prefer to avoid duplicating state information like that. Is there any built in way I can safely check if a communicator is valid?

Here is a basic program demonstrating my problem:

#include <mpi.h>
typedef struct {
  MPI_Comm comm;
} mystruct;


void cleanup(mystruct* a) {
  MPI_Comm_free(&(a->comm));
}

int main(int argc, char* argv[]) {
  MPI_Init(&argc, &argv);
  mystruct a;

  /* Some early exit condition triggers cleanup without
     initialization */
  cleanup(&a);
  MPI_Finalize();
  return 0;
}

Upvotes: 2

Views: 1005

Answers (1)

Zulan
Zulan

Reputation: 22670

MPI_COMM_NULL is a constant used for invalid communicators. However, you cannot determine if an MPI communicator has been initialized. In C, it is impossible to determine if a variable has been initialized. Non-static variables start with an indeterminate value, reading it causes undefined behavior.

You must initialized the communicator with MPI_COMM_NULL yourself. This only make sense if cannot possibly create actual communicator during initialization.

Note: MPI_Comm_free also sets comm to MPI_COMM_NULL.

Upvotes: 2

Related Questions