OpenMP C/C++ 指令格式
#pragma omp |
directive-name(名称) |
[clause, ...](语句) |
newline(换行符) |
Required for all OpenMP C/C++ directives. |
A valid OpenMP directive must appear after the pragma and before any clauses. |
Optional. Clauses can be in any order, and repeated as necessary unless otherwise restricted. |
Required. Precedes the structured block which is enclosed by this directive. |
构建并行区域
并行区域是被多个线程并发执行的代码块,通过如下指令构建并行区域,这是OpenMP的基础
#pragma omp parallel [clause ...]
- 当一个线程到达一个parallel指令时,它创建了一个线程组,并成为该组的主线程,主线程的线程编号为零。
- 进入并行区域后,代码块将被复制,所有线程都将执行该代码。
- 在并行区域的结尾有一个隐含的屏障,只有主线程在这一点之后继续执行。
- 如果任何线程在并行区域内终止,则该组中的所有线程都将终止,并且在那一点之前完成的工作是未定义的。
OpenMP helloworld
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int nthreads, tid;
//omp_set_num_threads(4); //设置4个线程
/* Fork a team of threads giving them their own copies of variables */
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
} /* All threads join master thread and disband */
return 0;
}