Goroutines in Co-array Fortran

Our example will demonstrate how to use coarray features in Fortran for concurrent programming. Here’s the full source code:

program main
    use, intrinsic :: iso_fortran_env, only: int8, sleep
    implicit none

    call execute_concurrently()

contains

    subroutine execute_concurrently()
        character(len=*), parameter :: msg1 = "direct", msg2 = "coarray", msg3 = "anonymous"
        integer :: i

        ! Synchronous execution
        call print_message(msg1)

        ! Asynchronous execution using coarray
        call print_message_coarray(msg2)

        ! Asynchronous execution with anonymous subroutine
        call print_anonymous("going")

        ! Wait for all coarrays to complete (simulate WaitGroup)
        call sleep(1, int8)

        print *, "done"
    end subroutine execute_concurrently

    subroutine print_message(from)
        character(len=*) :: from
        integer :: i

        do i = 0, 2
            print *, from, ':', i
        end do
    end subroutine print_message

    subroutine print_message_coarray(from)
        character(len=*) :: from
        integer :: i
        character(len=*), codimension[*] :: messages[*]

        messages[my_image()] = from
        sync all

        do i = 0, 2
            print *, messages[1], ':', i
        end do
    end subroutine print_message_coarray

    subroutine print_anonymous(msg)
        character(len=*) :: msg
        character(len=*), codimension[*] :: message[*]

        message[my_image()] = msg
        sync all

        print *, message[1]
    end subroutine print_anonymous

end program main

To run this program, compile and execute it with a Fortran compiler supporting coarrays. The program demonstrates both synchronous and asynchronous message printing using coarrays.

Here is how to compile and run the code:

$ gfortran -fcoarray=single -o coarrays coarrays.f90
$ ./coarrays
 direct : 0
 direct : 1
 direct : 2
 coarray : 0
 anonymous : 0
 anonymous : 1
 anonymous : 2
 done

This output shows the messages printed, with the asynchronous calls finishing after the synchronous ones.