Channels in Co-array Fortran

program channels
  use iso_fortran_env
  implicit none

  integer :: image
  character(len=4) :: msg

  ! In Co-array Fortran, we use co-arrays instead of channels
  character(len=4), codimension[*] :: message

  ! Only execute the following on image 1
  if (this_image() == 1) then
    ! Send a value to image 2
    message[2] = "ping"
    sync images(2)
  end if

  ! Only execute the following on image 2
  if (this_image() == 2) then
    sync images(1)
    ! Receive the value from image 1
    msg = message
    print *, msg
  end if

end program channels

In Co-array Fortran, we use co-arrays and image synchronization to achieve inter-image communication, which is conceptually similar to channels in other languages.

  1. We define a co-array message of type character with length 4. This co-array is used to pass data between images (similar to how channels pass data between goroutines).

  2. We use this_image() to determine which image (equivalent to a process or thread) the code is running on.

  3. On image 1, we assign the value “ping” to the message co-array on image 2 using the syntax message[2] = "ping". This is similar to sending a value into a channel.

  4. We use sync images(2) to synchronize image 1 with image 2, ensuring that the data is available before image 2 tries to read it.

  5. On image 2, we first synchronize with image 1 using sync images(1), then read the value from the message co-array into the local variable msg.

  6. Finally, we print the received message.

To run the program:

$ gfortran -coarray=single channels.f90 -o channels
$ ./channels
ping

By default, Co-array Fortran programs run with multiple images, allowing for parallel execution. The sync images statements ensure proper synchronization between the images, similar to how channel operations in other languages provide synchronization between concurrent processes.

In this example, we’ve used Co-array Fortran’s parallel features to mimic the behavior of channels in concurrent programming. While the concepts are not exactly the same, they serve similar purposes in enabling communication between parallel execution units.