Non Blocking Channel Operations in Co-array Fortran

Our program demonstrates non-blocking operations using Co-array Fortran. Here’s the full source code:

program non_blocking_operations
  use iso_fortran_env
  implicit none

  integer :: me, np
  character(len=20) :: message[*]
  logical :: signal[*]

  me = this_image()
  np = num_images()

  ! Here's a non-blocking receive. If a value is
  ! available on 'message', it will be received.
  ! If not, the program continues without waiting.
  if (me > 1) then
    if (message[me-1] /= '') then
      print *, 'Image ', me, ' received message: ', message[me-1]
    else
      print *, 'Image ', me, ' no message received'
    end if
  end if

  ! A non-blocking send works similarly.
  ! Here we attempt to send a message to the next image.
  if (me < np) then
    message[me+1] = 'hi'
    print *, 'Image ', me, ' sent message to image ', me+1
  else
    print *, 'Image ', me, ' no message sent'
  end if

  ! We can use multiple conditions to implement
  ! multi-way non-blocking operations.
  ! Here we attempt non-blocking receives on both
  ! 'message' and 'signal'.
  sync all
  if (me > 1) then
    if (message[me-1] /= '') then
      print *, 'Image ', me, ' received message: ', message[me-1]
    else if (signal[me-1]) then
      print *, 'Image ', me, ' received signal from image ', me-1
    else
      print *, 'Image ', me, ' no activity'
    end if
  end if

end program non_blocking_operations

To run the program, save the code in a file named non_blocking_operations.f90 and compile it using a Co-array Fortran-compatible compiler:

$ caf non_blocking_operations.f90 -o non_blocking_operations
$ cafrun -np 4 ./non_blocking_operations

This will run the program with 4 images (similar to processes or threads in other languages).

The program demonstrates non-blocking operations in Co-array Fortran:

  1. It first attempts a non-blocking receive. Each image (except the first) checks if there’s a message from the previous image without waiting.

  2. Then, it performs a non-blocking send. Each image (except the last) attempts to send a message to the next image.

  3. Finally, it demonstrates a multi-way non-blocking operation, where each image checks for either a message or a signal from the previous image.

In Co-array Fortran, these operations are naturally non-blocking due to the PGAS (Partitioned Global Address Space) model. The sync all statement is used to ensure all images have completed their operations before the final check.

This example showcases how Co-array Fortran can handle non-blocking operations in a parallel computing environment, which is conceptually similar to channel operations in other languages, but implemented using the co-array feature of Fortran.