Channel Directions in Fortran
In Fortran, we don’t have built-in channels like in some other languages. However, we can simulate similar behavior using derived types and procedures. This example demonstrates how to create a simple message passing system in Fortran.
module channel_module
implicit none
private
type, public :: channel
character(len=100) :: message
end type channel
public :: ping, pong
contains
subroutine ping(pings, msg)
type(channel), intent(inout) :: pings
character(len=*), intent(in) :: msg
pings%message = msg
end subroutine ping
subroutine pong(pings, pongs)
type(channel), intent(in) :: pings
type(channel), intent(out) :: pongs
pongs%message = pings%message
end subroutine pong
end module channel_module
program main
use channel_module
implicit none
type(channel) :: pings, pongs
call ping(pings, "passed message")
call pong(pings, pongs)
print *, trim(pongs%message)
end program mainIn this Fortran version:
We define a
channeltype in a module to simulate a channel-like structure.The
pingsubroutine takes achanneland a message as input. It sets the message in the channel.The
pongsubroutine takes two channels: one for input (pings) and one for output (pongs). It transfers the message from the input channel to the output channel.In the main program, we create two channel variables,
pingsandpongs.We call
pingto send a message through thepingschannel.We then call
pongto transfer the message frompingstopongs.Finally, we print the message received in the
pongschannel.
To run this Fortran program:
$ gfortran channel_directions.f90 -o channel_directions
$ ./channel_directions
passed messageThis example demonstrates how to implement a simple message passing system in Fortran, which is conceptually similar to channel directions in other languages. While Fortran doesn’t have built-in channel primitives, we can create similar behavior using derived types and procedures.