在Ubuntu中使用Fortran编写并行程序并利用MPI(Message Passing Interface)库,可以按照以下步骤进行:
首先,你需要安装MPI库。常用的MPI实现有Open MPI和MPICH。这里以Open MPI为例。
sudo apt update
sudo apt install libopenmpi-dev
假设你已经有了一个简单的Fortran程序,现在我们要将其修改为使用MPI。
hello_mpi.f90
program hello_mpi
use mpi
implicit none
integer :: ierr, rank, size
! Initialize MPI
call MPI_INIT(ierr)
! Get the rank of the process
call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr)
! Get the number of processes
call MPI_COMM_SIZE(MPI_COMM_WORLD, size, ierr)
! Print the message
if (rank == 0) then
print *, 'Hello from process', rank, 'of', size
else
print *, 'Hello from process', rank
end if
! Finalize MPI
call MPI_FINALIZE(ierr)
end program hello_mpi
使用mpif90
编译器来编译你的Fortran代码。mpif90
是Open MPI提供的Fortran编译器包装器。
mpif90 -o hello_mpi hello_mpi.f90
使用mpiexec
或mpirun
命令来运行你的MPI程序。你需要指定要运行的进程数。
mpiexec -n 4 ./hello_mpi
或者使用mpirun
:
mpirun -np 4 ./hello_mpi
这里的-n 4
或-np 4
表示运行4个进程。
你应该会看到类似以下的输出:
Hello from process 0 of 4
Hello from process 1
Hello from process 2
Hello from process 3
这表明你的MPI程序已经成功运行,并且每个进程都打印了自己的rank和总进程数。
通过以上步骤,你可以在Ubuntu中使用Fortran编写并运行MPI程序。关键步骤包括安装MPI库、编写Fortran代码、编译代码以及运行程序。希望这些信息对你有所帮助!