Open Multi-Processing的缩写,是一个应用程序接口(API),可用于显式指导多线程、共享内存的并行性。
在项目程序已经完成好的情况下不需要大幅度的修改源代码,只需要加上专用的pragma来指明自己的意图,由此编译器可以自动将程序进行并行化,并在必要之处加入同步互斥以及通信。当选择忽略这些pragma,或者编译器不支持OpenMp时,程序又可退化为通常的程序(一般为串行),代码仍然可以正常运作,只是不能利用多线程来加速程序执行。OpenMP提供的这种对于并行描述的高层抽象降低了并行编程的难度和复杂度,这样程序员可以把更多的精力投入到并行算法本身,而非其具体实现细节。对基于数据分集的多线程程序设计,OpenMP是一个很好的选择。
OpenMP支持的语言包括C/C++、Fortran;而支持OpenMP的编译器VS、gcc、clang等都行。可移植性也很好:Unix/Linux和Windows
OpenMP编程模型
内存共享模型:OpenMP是专为多处理器/核,共享内存机器所设计的。底层架构可以是UMA和NUMA。即(Uniform Memory Access和Non-Uniform Memory Access)
基于线程的并行性
明确的并行
Fork-Join模型
数据范围
嵌套并行
动态线程
在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个线程并行执行,没有确定的先后顺序)
也可以直接使用gcc加上-fopenmp编译,For example:
1 g++ test.cpp -o test -fopenmp
2 ./test
(不知道我的gcc不行,只能用g++,枯了)
补:直到原因了,gcc默认编译链接不会链接C++标准库,可以使用g++编译链接(如上),也可以在gcc链接时显示指定链接 -lstdc++
gcc test.cpp -o test -fopenmp -lstdc++
原文:https://www.cnblogs.com/ybqjymy/p/13679547.html