Coarrays

Images and this_image

A coarray program runs as several copies called images, and each image executes the same code with its own number.

The this_image function returns the number of the current image, while num_images returns the total count.

The program below greets the user once per image with its own number attached.

program demo implicit none print *, "hello from image", this_image() print *, "of", num_images() end program demo

Coarray syntax

A coarray declaration adds square brackets to a normal declaration, giving every image its own copy of the variable.

An undecorated name means the local copy, while a name with brackets in square form reads the copy on another image.

Here each image stores its own number and image one collects the value from image two.

program demo implicit none integer :: me[*] me = this_image() sync all if (this_image() == 1) print *, me[2] end program demo

SYNC ALL

Images run at their own pace, so a sync all statement is the meeting point where every image waits for all the others.

Place it after remote writes and before remote reads, so no image reads data that a slower image has not stored yet.

The sketch writes a value for the neighbor, synchronizes, and only then reads the neighbor value.

program demo implicit none integer :: slot[*] slot = this_image() * 10 sync all if (this_image() == 1) print *, slot[num_images()] sync all end program demo

Run on images

A normal run starts a single image, while a coarray launcher starts several images of the same program at once.

gfortran refuses coarray code without a flag, so the first build below asks for single-image mode: the program runs as one image and every coarray behaves like a plain variable.

Several images need the OpenCoarrays library: build with -fcoarray=lib and link the library, then start the program with cafrun -n 4 ./a.out. That launcher is not part of gfortran itself, so the multi-image run is not repeated here.

gfortran -fcoarray=single demo.f90 -o demo && ./demo

hello from image 1
of 1

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container, in single-image mode; the multi-image run needs OpenCoarrays.

Article author: Arthur Isaev