Exit in Co-array Fortran

Here’s an idiomatic Co-array Fortran example demonstrating the concept of program exit:

program exit_example
  use iso_fortran_env, only: error_unit
  implicit none

  ! Declare a co-array variable
  integer :: status[*]

  ! Set an exit status
  status = 3

  ! Print a message before exiting
  print *, "Exiting program on image", this_image()

  ! Synchronize all images before exiting
  sync all

  ! Exit the program with the specified status
  if (this_image() == 1) then
    call exit(status)
  end if

  ! This line will not be executed on image 1
  print *, "This message won't be printed on image 1"

end program exit_example

This Co-array Fortran program demonstrates how to exit a program with a specific status code. Let’s break down the key elements:

  1. We use the iso_fortran_env module to access the error_unit constant, which is the standard error output unit.

  2. 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.

  3. We set the exit status to 3, similar to the Go example.

  4. We print a message indicating which image is exiting. The this_image() function returns the current image number.

  5. We use sync all to synchronize all images before exiting. This ensures that all images reach this point before proceeding.

  6. We use an if statement to check if the current image is 1. Only image 1 will call the exit subroutine with the specified status.

  7. 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:

  1. Save the code in a file named exit_example.f90.
  2. Compile the program using a Fortran compiler that supports Co-array Fortran, such as gfortran with OpenCoarrays:
$ caf exit_example.f90 -o exit_example
  1. Run the program with multiple images:
$ cafrun -np 4 ./exit_example

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:

$ echo $?
3

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.