几点说明 口OpenMP程序编写 ●通常采用增量并行方法:逐步改造现有的串行程序,每次只对部分代 码进行并行化,这样可以逐步改造,逐步调试。 C/C++的OpenMP指令标识符为#pragma omp ·C/C++程序中,OpenMP指令区分大小写 每个OpenMP指令后是一个结构块(用大括号括起来) 口源程序编译 gcc -fopenmp OMP_hello.c -o OMP hello icc -openmp OMP_hello.c -o OMP hello /Intel C http://math.ecnu.edu.cn/~jypan 11
http://math.ecnu.edu.cn/~jypan 11 几点说明 OpenMP 程序编写 ► 通常采用增量并行方法:逐步改造现有的串行程序,每次只对部分代 码进行并行化,这样可以逐步改造,逐步调试。 ► C/C++ 的 OpenMP 指令标识符为 #pragma omp ► C/C++ 程序中,OpenMP 指令区分大小写 ► 每个 OpenMP 指令后是一个结构块(用大括号括起来) 源程序编译 gcc –fopenmp OMP_hello.c –o OMP_hello icc –openmp OMP_hello.c –o OMP_hello // Intel C
华东师范大学数学科学学院 School of Mathematical Sciences,ECNU OpenMP编程三要素 a编译指导(Compiler Directive) ▣运行库函数(Runtime Library Routines) 口环境变量(Environment Variables) http://math.ecnu.edu.cn/~jypan
http://math.ecnu.edu.cn/~jypan 华东师范大学 数学科学学院 School of Mathematical Sciences, ECNU 编译指导(Compiler Directive) 运行库函数(Runtime Library Routines) 环境变量(Environment Variables) OpenMP 编程三要素
编译指导指令 OpenMP通过对串行程序添加编译指导指令实现并行化 编译指导指令分类 ·并行域指令:创建并行域,即产生多个线程以并行方式执行任务,所 有并行任务必须放在并行域中才能被并行执行 ·工作共享指令:负责任务划分,并分发给各个线程,工作共享指令不 能产生新线程,因此必须位于并行域中 ●同步指令:负责并行线程之间的同步 数据环境:负责并行域内的变量的属性(共享或私有),以及边界上 (串行域与并行域)的数据传递 http://math.ecnu.edu.cn/-jypan 13
http://math.ecnu.edu.cn/~jypan 13 编译指导指令 OpenMP 通过对串行程序添加编译指导指令实现并行化 并行域指令:创建并行域,即产生多个线程以并行方式执行任务,所 有并行任务必须放在并行域中才能被并行执行 工作共享指令:负责任务划分,并分发给各个线程,工作共享指令不 能产生新线程,因此必须位于并行域中 同步指令:负责并行线程之间的同步 数据环境:负责并行域内的变量的属性(共享或私有),以及边界上 (串行域与并行域)的数据传递 编译指导指令分类
并行域 ●并行域指令Parallel Constructs parallel 创建一个并行域 #pragma omp parallel private(tid) tid=omp_get_thread_num();/Obtain thread id printf("Hello world from OpenMP thread %d\n",tid); if (tid==0)//Only master thread does this { nthreads=omp_get_num_threads(); printf("Number of threads:%d\n",nthreads); OMP hello.c http://math.ecnu.edu.cn/~jypan 14
http://math.ecnu.edu.cn/~jypan 14 并行域 并行域指令 Parallel Constructs parallel 创建一个并行域 #pragma omp parallel private(tid) { tid=omp_get_thread_num(); // Obtain thread id printf("Hello world from OpenMP thread %d\n", tid); if (tid==0) // Only master thread does this { nthreads=omp_get_num_threads(); printf("Number of threads: %d\n", nthreads); } } OMP_hello.c
工作共享 工作共享结构Work-Sharing Constructs for 创建循环共享结构,代表典型的数据并行 sections 创建sections结构,将任务划分成独立的子任务(section), /section 每个子任务由一个线程执行,典型的任务并行 创建仅由一个线程执行的任务,先到先执行,其他线程等 single 待其执行结束后再一起执行后面的任务 与single类似,但指定由主线程执行,而且其他线程无需 master 等待 task 创建一个显式任务,可以立即被执行,也可以挂起并推迟 taskyield 执行,便于实现一些复杂结构,如递归。 workshare 仅适用Fortran http://math.ecnu.edu.cn/-jypan 15
http://math.ecnu.edu.cn/~jypan 15 工作共享 工作共享结构 Work-Sharing Constructs for 创建循环共享结构,代表典型的数据并行 sections /section 创建 sections 结构,将任务划分成独立的子任务(section), 每个子任务由一个线程执行,典型的任务并行 single 创建仅由一个线程执行的任务,先到先执行,其他线程等 待其执行结束后再一起执行后面的任务 master 与 single 类似,但指定由主线程执行,而且其他线程无需 等待 task taskyield 创建一个显式任务,可以立即被执行,也可以挂起并推迟 执行,便于实现一些复杂结构,如递归。 workshare 仅适用 Fortran