[petsc-users] petsc init in class constructor

Karl Rupp rupp at iue.tuwien.ac.at
Thu Oct 6 03:39:59 CDT 2016


Hi,

> I would like to write a c++ class which solve a linear system with petsc (code as following).
> Petsc is used only in this class. So I call MPI_Init in main.cpp, but PetscInitialize and PetscFinalise are in constructor/destructor of class.
> I am wondering if this way is safe?
>
> class solvepetsc{
>
> 	solvepetsc(int argc, char** argv){
> 		PetscInitialize(&argc, &argv, NULL, NULL);
> 	};
>
> 	~solvepetsc(){
> 		PetscFinalize();
> 	};
>
> 	// ...
> }

well, you could do it this way, but the devil's in the detail: You 
should check the return value of PetscInitialize() and PetscFinalize() 
for error checking.

Now, how do you plan to deal with an error in PetscInitialize()? You 
can't throw an exception, because that will terminate your program 
immediately. Delaying the error checks is likely to be fragile.

Another question: How do you instances of solvepetsc do you expect? If 
you have more than one instance in use at the same time, you will run 
into problems due to an oversubscription of the internal global 
variables (logging, etc.).

Long story short: I'd encourage you not to initialize PETSc in a 
constructor, unless you know exactly what you are doing and can control 
the possible side effects.

Best regards,
Karli



More information about the petsc-users mailing list