什么是OpenMP
Open Multi-Processing的缩写,是一个应用程序接口(API),可用于显式指导多线程、共享内存的并行性。
在项目程序已经完成好的情况下不需要大幅度的修改源代码,只需要加上专用的pragma来指明自己的意图,由此编译器可以自动将程序进行并行化,并在必要之处加入同步互斥以及通信。当选择忽略这些pragma,或者编译器不支持OpenMp时,程序又可退化为通常的程序(一般为串行),代码仍然可以正常运作,只是不能利用多线程来加速程序执行。OpenMP提供的这种对于并行描述的高层抽象降低了并行编程的难度和复杂度,这样程序员可以把更多的精力投入到并行算法本身,而非其具体实现细节。对基于数据分集的多线程程序设计,OpenMP是一个很好的选择。
OpenMP支持的语言包括C/C++、Fortran;而支持OpenMP的编译器VS、gcc、clang等都行。可移植性也很好:Unix/Linux和Windows
简单使用
在VS2017中就可以使用,具体的:新建一个C/C++程序,项目--属性--C/C++--语言--OpenMP支持,把OpenMP打开。然后编写带编译指令的并行程序,注意一定要加上<omp.h>头文件。
写一个并行的Hello World
1 #include <omp.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main() 6 { 7 int nthreads, tid; 8 9 /* Fork a team of threads giving them their own copies of variables */ 10 #pragma omp parallel private(nthreads, tid) 11 { 12 13 /* Obtain thread number */ 14 tid = omp_get_thread_num(); 15 printf("Hello World from thread = %d\n", tid); 16 17 /* Only master thread does this */ 18 if (tid == 0) 19 { 20 nthreads = omp_get_num_threads(); 21 printf("Number of threads = %d\n", nthreads); 22 } 23 24 } /* All threads join master thread and disband */ 25 return 0; 26 }
运行结果如下:
注:我的电脑默认是4个线程,不同的电脑运行结果不同,就算是同一部电脑每次运行的结果也可能不同(4个线程并行执行,没有确定的先后顺序)
至于OpenMP详细的编写格式和意义可以看这篇博客。
参考资料:
1、https://blog.csdn.net/wyjkk/article/details/6612108
2、https://blog.csdn.net/HW140701/article/details/73716363
3、https://computing.llnl.gov/tutorials/openMP/#RunTimeLibrary