A simple tutorial on using openmp on Tianhe supercomputer

The first step is to log in to the Tianhe supercomputer.
The second step is to create a folder for installing the test program, mkdir test_openmp
The third step is to create an openmp parallel program hello.c, and write the following code:

#include<stdio.h>
int main(int argc, char** argv){
    
    
  int i;
  int max = 0;
  #pragma omp parallel for private(i) reduction(max:max)
  for(i=0;i<=10000;i++){
    
    
    if(i>max)max=i;
  }
  printf("%d\n",max);
}

The fourth step, compile:

gcc -o hello hello.c -fopenmp

The fifth step is to adjust the environment variable OMP_NUM_THREADS that controls the number of threads. If it is not adjusted according to the maximum number of supported threads, that is, the number of cpu cores, the number of parallel threads is adjusted to 2 here:

export OMP_NUM_THREADS=2

Step 6: Run:

./hello

Output result:

10000

Core code explanation:

#pragma omp parallel for private(i) reduction(max:max)

#代表通过openmp多线程并行
#pragma omp parallel

#代表通过openmp多线程并行,并且只并行for循环的内容
#pragma omp parallel for

#代表通过openmp多线程并行,并且只并行for循环的内容,并且每个线程有一个独立的迭代器i
#pragma omp parallel for private(i)

#代表通过openmp多线程并行,并且只并行for循环的内容,并且每个线程有一个独立的迭代器i,并且计算之后取所有并行结果的最大值
#pragma omp parallel for private(i) reduction(max:max)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324344152&siteId=291194637