OpenMP常用指令释义
1 #pragma omp for
int j = 0;
#pragma omp for
for ( j = 0; j < 4; j++ ){
printf(“j = %d, ThreadId = %d\n”, j, omp_get_thread_num());
}
执行以上代码后打印出以下结果
j = 0, ThreadId = 0
j = 1, ThreadId = 0
j = 2, ThreadId = 0
j = 3, ThreadId = 0
单独使用for,后续循环在一个线程中执行。可以看出没有形成多线程的效果,所以一般不推荐使用。
2 #pragma omp parallel
int j = 0;
#pragma omp parallel for
for ( j = 0; j < 4; j++ ){
printf(“j = %d, ThreadId = %d\n”, j, omp_get_thread_num());
}
执行后会打印出以下结果:
j = 0, ThreadId = 0
j = 2, ThreadId = 2
j = 1, ThreadId = 1
j = 3, ThreadId = 3
区域并行化指导语句,说明后续语句按多线程方式运行,线程数默认为CPU线程数,也可以用num_threads()自行指定。
3 #pragma omp parallel for
#pragma omp parallel
{
#pragma omp for
for ( j = 0; j < 4; j++ ){
printf(“j = %d, ThreadId = %d\n”, j, omp_get_thread_num());
}
}
执行以上代码会打印出以下结果:
j = 1, ThreadId = 1
j = 3, ThreadId = 3
j = 2, ThreadId = 2
j = 0, ThreadId = 0
循环并行化指导语句,说明后续循环按多线程执行,线程数与循环次数相等。