Channel Synchronization in Fortran

Here’s the Fortran translation of the channel synchronization example:

Our first program demonstrates how to synchronize execution across different processes. Here’s the full source code:

program channel_synchronization
    use, intrinsic :: iso_fortran_env, only: int64
    implicit none
    
    integer :: ierr
    integer(int64) :: count_rate, t1, t2
    
    call worker()
    
contains

subroutine worker()
    write(*, '(a)', advance='no') 'working...'
    call system_clock(t1, count_rate)
    
    ! Simulate work with a sleep
    do while (t2 - t1 < count_rate)
        call system_clock(t2)
    end do
    
    write(*, '(a)') 'done'
end subroutine worker

end program channel_synchronization

This is the subroutine we’ll run to simulate work. The worker subroutine prints a message, waits for one second, and then prints another message.

In the main program, we simply call the worker subroutine. Unlike concurrent programming models, Fortran doesn’t have built-in constructs for goroutines or channels. Instead, we use a sequential approach here.

To run the program, compile the code and then execute the resulting binary:

$ gfortran channel_synchronization.f90 -o channel_synchronization
$ ./channel_synchronization
working...done

In this Fortran version, we’ve simulated the delay using a simple timing loop. Fortran doesn’t have a direct equivalent to goroutines or channels, so we’ve adapted the example to demonstrate a similar concept of a worker routine that performs a task with a delay.

For more complex synchronization in Fortran, you might use features like OpenMP for shared-memory parallelism or MPI for distributed-memory parallelism, but these are beyond the scope of this basic example.