开始尝试在 Win7 下使用 OpenMP 编写 fortran 并行程序

备忘:

  • 使用 VS2013 + IVF2013 SP1 update1 / gfortran 4.9.2
  • 没有专门下载 OpenMP,直接使用 IDE 进行编辑和运行
  • VS需要对 Project 的属性设置一下:打开Generate Parallel Code (/Qopenmp) / Gfortran 需要使用 -fopenmp
  • 未设置环境变量
开始尝试在 Win7 下使用 OpenMP 编写 fortran 并行程序_第1张图片
教程中给的例子

1. 实例

教程: Parallel Programming in Fortran 95 using OpenMP
使用 OpenMP 应该算是一种比较简单的并行方式,用

!$OMP PARALLEL

!$OMP END PARALLEL

将需要并行的部分放进去就行了。

开始尝试在 Win7 下使用 OpenMP 编写 fortran 并行程序_第2张图片
我自己运行的结果

gfortran 编译的话使用 -fopenmp 选项即可

开始尝试在 Win7 下使用 OpenMP 编写 fortran 并行程序_第3张图片
gfortran 编译的话使用 -fopenmp 选项即可

如果不是并行程序的话,仅仅会输出一次,但是这里输出了 4 次,因为有四个线程。而教程中也对这个做了解释:

Since the code enclosed between the two directives is executed by each thread, the message Hello appears in the screen as many times as threads are being used in the parallel region.

不知道那个控制台的图标为啥变成了四个红点,是不是点的个数表示线程数呢?


2. 基础语法

One of the aims of the OpenMP standard is to offer the possibility of using the same source code lines with an OpenMP-compliant compiler and with a normal compiler. This can only be achieved by hiding the OpenMP directives and commands in such a way, that a normal compiler is unable to see them. For that purpose the following two directive sentinels are introduced: !$OMP & !$

需要注意的是 !$OMP 前面不能出现非空字符,否则将会被认为是普通的注释。OMP的这种方式可以很巧妙地使得程序能够在所有的编译器上运行,如果不支持OMP的话就当作普通的注释,如果支持那么这些就会起作用。另外 指令后面有一个空格,这个主要是为了 指令和后面的语句分隔开。这个空格是强制添加的,否则将作为普通注释来处理。

OMP 的指令行支持续行,和 fortran 没多大区别,只要记得每一行都有指令符号就行了。

!$OMP PARALLEL DEFAULT(NONE) SHARED(A, B) PRIVATE(C, D) &
!$OMP REDUCTION(+:A)

暂时就学了这么点。。。

你可能感兴趣的:(开始尝试在 Win7 下使用 OpenMP 编写 fortran 并行程序)