OpenMP入门(2)条件编译和查看线程数的函数

一般情况下,源程序中所有的行都参加编译。但有时希望对其中一部分内容只在满足一定条件下才进行编译,即对一部分内容指定编译条件,这就是“条件编译”(conditional compile)[1]。

OpenMP中的条件编译语句:

#ifdef _OPENMP

#endif

这两行中间的源程序只会在并行编译时才会被编译

下面我们学习两个跟线程数目相关的常用函数:

  • omp_get_num_threads() 获得线程总数
  • omp_get_thread_num() 获得当前线程序号

更多函数请参考
https://msdn.microsoft.com/en-us/library/k1h4zbed.aspx

下面让我们看一个例子以便更好地理解上面的知识:

test.c :

#ifdef _OPENMP
#include 
##endif

int main(){
#pragma omp parallel
 {
#ifdef _OPENMP
    printf("I am thread %d / %d \n",
    omp_get_thread_num(),omp_get_num_threads());
#else
    printf("I am sequentiel \n");
#endif
 }
}

编译,运行及结果:
编译成普通c程序:

$gcc test.c -o test
$./test
I am sequentiel

编译成并行程序:

$gcc -fopenmp test.c -o test_openmp
$export OMP_NUM_THREADS=4
$./test_openmp
I am thread 0 / 4
I am thread 3 / 4
I am thread 1 / 4
I am thread 2 / 4

各线程计算速度相近,所以顺序并不是按照序号排列的。

[1]http://baike.baidu.com/view/1995627.htm

你可能感兴趣的:(高性能运算/并行编程)