xref: /petsc/src/sys/tutorials/ex4.c (revision 0ea77eda237b1068ff0d8bfa28c3463dc2087695)
1 static char help[] = "Introductory example that illustrates running PETSc on a subset of processes.\n\n";
2 
3 #include <petscsys.h>
4 
5 int main(int argc, char *argv[]) {
6   PetscMPIInt rank, size;
7 
8   /* We must call MPI_Init() first, making us, not PETSc, responsible for MPI */
9   PetscCallMPI(MPI_Init(&argc, &argv));
10 #if defined(PETSC_HAVE_ELEMENTAL)
11   PetscCall(PetscElementalInitializePackage());
12 #endif
13   /* We can now change the communicator universe for PETSc */
14   PetscCallMPI(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
15   PetscCallMPI(MPI_Comm_split(MPI_COMM_WORLD, rank % 2, 0, &PETSC_COMM_WORLD));
16 
17   /*
18     Every PETSc routine should begin with the PetscInitialize() routine.
19     argc, argv - These command line arguments are taken to extract the options
20                  supplied to PETSc and options supplied to MPI.
21     help       - When PETSc executable is invoked with the option -help,
22                  it prints the various options that can be applied at
23                  runtime.  The user can use the "help" variable place
24                  additional help messages in this printout.
25   */
26   PetscFunctionBeginUser;
27   PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
28 
29   /*
30      The following MPI calls return the number of processes
31      being used and the rank of this process in the group.
32    */
33   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
34   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
35 
36   /*
37      Here we would like to print only one message that represents
38      all the processes in the group.  We use PetscPrintf() with the
39      communicator PETSC_COMM_WORLD.  Thus, only one message is
40      printed representng PETSC_COMM_WORLD, i.e., all the processors.
41   */
42   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Number of processors = %d, rank = %d\n", size, rank));
43 
44   /*
45      Always call PetscFinalize() before exiting a program.  This routine
46        - finalizes the PETSc libraries as well as MPI
47        - provides summary and diagnostic information if certain runtime
48          options are chosen (e.g., -log_view).  See PetscFinalize()
49      manpage for more information.
50   */
51   PetscCall(PetscFinalize());
52   PetscCallMPI(MPI_Comm_free(&PETSC_COMM_WORLD));
53 #if defined(PETSC_HAVE_ELEMENTAL)
54   PetscCall(PetscElementalFinalizePackage());
55 #endif
56   /* Since we initialized MPI, we must call MPI_Finalize() */
57   PetscCallMPI(MPI_Finalize());
58   return 0;
59 }
60 
61 /*TEST
62 
63    test:
64       nsize: 5
65       args: -options_left no
66       filter: sort -b | grep -v saws_port_auto_selectcd
67       filter_output: sort -b
68 
69 TEST*/
70