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 timeoutsRunning this program shows the first operation timing out and the second succeeding.
$ gfortran timeouts.f90 -o timeouts
$ ./timeouts
timeout 1
result 2In this Fortran version:
We use the
sleepsubroutine to simulate a long-running operation.We use
system_clockto measure elapsed time and implement timeouts.Instead of channels and goroutines, we use simple sequential execution and time checking.
The
selectstatement is replaced withif-elseconditions 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.