Our program demonstrates the use of a synchronization mechanism similar to WaitGroups in Co-array Fortran. Here’s the full source code:
This is the main program that demonstrates the concept of synchronization in Co-array Fortran:
We use the iso_fortran_env module for access to the num_images() function.
We declare a co-array variable counter to keep track of completed tasks across all images.
We launch 5 worker tasks using a do loop.
After launching all tasks, we use sync all to wait for all images to complete their work.
The worker subroutine simulates an expensive task:
It prints a message when starting and finishing.
It uses the sleep function to simulate work (note: sleep is not standard Fortran, you may need to use a different method depending on your compiler).
After completing, it increments the shared counter on image 1.
To run the program, compile it with a Co-array Fortran-capable compiler and execute it:
The order of workers starting up and finishing is likely to be different for each invocation and will depend on the number of images used.
Note that this approach uses Co-array Fortran’s built-in synchronization mechanisms. For more advanced use cases, you might need to implement custom synchronization routines or use additional libraries.