在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代碼、編譯代碼以及運行程序。希望這些信息對你有所幫助!