Timeouts in Fortran

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in Fortran can be achieved using the sleep subroutine and checking elapsed time.

program timeouts
    use, intrinsic :: iso_fortran_env
    implicit none
    
    integer :: start_time, current_time, count_rate
    character(len=20) :: result

    ! For our example, suppose we're executing an external
    ! call that returns its result after 2 seconds.
    call system_clock(start_time, count_rate)
    call sleep(2)
    result = "result 1"

    ! Here we implement a timeout. We check if more than 1 second
    ! has passed since we started waiting.
    call system_clock(current_time)
    if ((current_time - start_time) / real(count_rate) > 1.0) then
        print *, "timeout 1"
    else
        print *, result
    end if

    ! If we allow a longer timeout of 3 seconds, then we'll
    ! successfully get the result.
    call system_clock(start_time)
    call sleep(2)
    result = "result 2"

    call system_clock(current_time)
    if ((current_time - start_time) / real(count_rate) > 3.0) then
        print *, "timeout 2"
    else
        print *, result
    end if

end program timeouts

Running this program shows the first operation timing out and the second succeeding.

$ gfortran timeouts.f90 -o timeouts
$ ./timeouts
timeout 1
result 2

In this Fortran version:

  1. We use the sleep subroutine to simulate a long-running operation.

  2. We use system_clock to measure elapsed time and implement timeouts.

  3. Instead of channels and goroutines, we use simple sequential execution and time checking.

  4. The select statement is replaced with if-else conditions checking the elapsed time.

Note that Fortran doesn’t have built-in support for concurrent execution like Go’s goroutines. For more complex scenarios involving true parallelism or concurrency, you might need to use Fortran’s coarray features or external libraries for parallel programming.