Select in Co-array Fortran
Our example demonstrates the use of multiple image synchronization in Co-array Fortran. This is similar to selecting across multiple channels in other languages.
program select_example
use iso_fortran_env
implicit none
integer :: i
character(len=10) :: msg[*]
! Simulate two different operations
if (this_image() == 1) then
call sleep(1)
msg = "one"
else if (this_image() == 2) then
call sleep(2)
msg = "two"
end if
! Synchronize all images
sync all
! Print messages as they arrive
if (this_image() == 1) then
do i = 1, 2
if (msg[i] /= "") then
print *, "received ", msg[i]
end if
end do
end if
end program select_exampleIn this example, we use Co-array Fortran’s parallel execution model to simulate concurrent operations. Each image (similar to a goroutine) performs a different operation.
We define a co-array
msgthat can hold a string message.Depending on the image number, we simulate different operation times using the
sleepsubroutine and set different messages.We use
sync allto ensure all images have completed their operations before proceeding.Finally, the first image checks and prints the messages from all images.
To run the program:
$ gfortran -fcoarray=lib select_example.f90 -o select_example
$ ./select_example
received one
received twoNote that the total execution time will be approximately 2 seconds, as both the 1 and 2 second sleep operations execute concurrently on different images.
This example demonstrates how Co-array Fortran can be used to perform concurrent operations and synchronize between different images, similar to selecting across multiple channels in other languages.