在C/C++和Fortran中,都有编译器支持OpenMP,这里我们举一个简单的C程序的例子
test.c :
#ifdef _OPENMP
#include <omp.h>
#endif
int main(){
#pragma omp parallel
{
printf("is parallel ! \n");
printf("Always // \n");
}
printf("is sequential \n");
}
其中#pragma omp <directive> [clause[[,] clause] ...]
是OpenMP的语法结构。directive 有11种,parallel 代表接下来的代码块将被多个线程并行各执行一遍。其他的directive我会在后续的文章中讲解。
test2.c:
#ifdef _OPENMP
#include <omp.h>
#endif
int main(){
#pragma omp parallel{
printf("is parallel ! \n");
}
printf("is sequential \n");
}
编译:
下面是两种编译方法,第一行是编译成普通的c程序
第二行是编译成并行化程序
gcc test2.c -o test2
gcc -fopenmp test2.c -o test2_openmp
运行test2与其结果:
$./test2
is parallel !
is sequential
运行test2_openmp与结果:
$export OMP_NUM_THREADS=4
$./test2_openmp
is parallel !
is parallel !
is parallel !
is parallel !
is sequential
通过export指令我们把线程数设置为4,所以输出is parallel !结果4次。
如果#pragma omp parallel后面没有中括号,它只对紧跟着的那条指令并行化:
test3.c
#ifdef _OPENMP
#include <omp.h>
#endif
int main(){
#pragma omp parallel
printf("is parallel ! \n");
printf("is sequential \n");
}
test2.c 和 test3.c 是一样的。
在下一篇文章中我会为大家介绍OpenMP条件编译和几个常用函数。
http://blog.csdn.net/liuxingrui4p/article/details/44118297