在Ubuntu上使用Fortran进行并行计算,通常有两种主要方法:使用OpenMP进行共享内存并行计算,或者使用MPI进行分布式内存并行计算。以下是详细步骤和示例代码:
sudo apt-get update
sudo apt-get install gfortran
program parallel_example
use omp_lib
implicit none
integer :: i, n = 10
!$omp parallel do private(i)
do i = 1, n
print *, 'Thread ', omp_get_thread_num(), ' executing iteration ', i
end do
!$omp end parallel do
end program parallel_example
-fopenmp
选项以启用OpenMP支持。gfortran -fopenmp parallel_example.f90 -o parallel_example
./parallel_example
sudo apt-get update
sudo apt-get install openmpi-bin openmpi-common libopenmpi-dev
program mpi_example
use mpi
implicit none
integer :: rank, size, ierr
call MPI_Init(ierr)
call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierr)
call MPI_Comm_size(MPI_COMM_WORLD, size, ierr)
print *, 'Hello from process ', rank, ' of ', size
call MPI_Finalize(ierr)
end program mpi_example
mpif90
编译器并链接MPI库。mpif90 mpi_example.f90 -o mpi_example
mpiexec
或mpirun
命令来启动并行程序,并指定进程数。mpiexec -n 4 ./mpi_example