Exit in Co-array Fortran
Here’s an idiomatic Co-array Fortran example demonstrating the concept of program exit:
This Co-array Fortran program demonstrates how to exit a program with a specific status code. Let’s break down the key elements:
We use the
iso_fortran_env
module to access theerror_unit
constant, which is the standard error output unit.We declare a co-array variable
status
to store the exit status code. In Co-array Fortran, this variable is shared across all images (parallel instances) of the program.We set the exit status to 3, similar to the Go example.
We print a message indicating which image is exiting. The
this_image()
function returns the current image number.We use
sync all
to synchronize all images before exiting. This ensures that all images reach this point before proceeding.We use an
if
statement to check if the current image is 1. Only image 1 will call theexit
subroutine with the specified status.The last print statement demonstrates that it won’t be executed on image 1, as the program will have already exited.
To compile and run this Co-array Fortran program:
- Save the code in a file named
exit_example.f90
. - Compile the program using a Fortran compiler that supports Co-array Fortran, such as gfortran with OpenCoarrays:
- Run the program with multiple images:
This will run the program with 4 images. You’ll see output from each image, but only image 1 will actually exit with the specified status code.
To check the exit status after running the program, you can use:
Note that in Co-array Fortran, unlike C or Go, we use the exit
subroutine to terminate the program with a specific status code. The stop
statement can also be used, but it doesn’t allow specifying a custom status code.
This example demonstrates how to handle program exit in a parallel Co-array Fortran program, ensuring proper synchronization before termination.