在 Ubuntu 上进行 Fortran 并行计算,常见方式有以下几种,从简单到高级给你梳理一下,并附上示例和编译方法。
适合:单机多核并行
sudo apt update
sudo apt install gfortran
program omp_test
use omp_lib
implicit none
integer :: i, nthreads
!$omp parallel
nthreads = omp_get_num_threads()
print *, "Hello from thread", omp_get_thread_num(), "of", nthreads
!$omp end parallel
end program omp_test
gfortran -fopenmp omp_test.f90 -o omp_test
./omp_test
设置线程数:
export OMP_NUM_THREADS=4
./omp_test
适合:集群、超算、多节点
sudo apt install mpich
或
sudo apt install openmpi-bin libopenmpi-dev
program mpi_test
use mpi
implicit none
integer :: ierr, rank, size
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_test
mpif90 mpi_test.f90 -o mpi_test
mpirun -np 4 ./mpi_test
mpif90 -fopenmp hybrid.f90 -o hybrid
mpirun -np 2 ./hybrid
(每个 MPI 进程再用 OpenMP 多线程)
program coarray_test
implicit none
print *, "Hello from image", this_image(), "of", num_images()
end program
gfortran -fcoarray=lib coarray_test.f90 -o coarray_test
./coarray_test
或
gfortran -fcoarray=single coarray_test.f90 -o coarray_test
| 需求 | 推荐方式 |
|---|---|
| 单机多核 | OpenMP |
| 多机/集群 | MPI |
| 简单科学计算 | OpenMP |
| 大规模数值模拟 | MPI / MPI+OpenMP |
| 想用现代 Fortran | Coarray |
use omp_lib确保加了:
-fopenmp
确认:
which mpirun
schedule 优化 OpenMPperf / gprof 分析如果你有具体的 Fortran 程序或计算问题(如矩阵计算、循环并行、CFD、数值积分等),可以直接发代码,我可以帮你改成并行版本。