原文:https://www.bearoom.xyz/2019/02/17/openmp1/

并行技术有很多种,OpenMP算是比较简单可用的一种,OpenMP全称是 Open Multi-Processing ,是一个支持共享存储并行设计的库.

OpenMP 支持的编程语言有C、C++和Fortran,支持OpenMP的编译器包括Sun Compiler,GNU Compiler和Intel Compiler等。在VS中打开OpenMP,需要打开属性->C/C+±>语言->OpenMP支持的设置即可;其他平台编译的时候打开OpenMP的标识如下:

一个VS中的简单例子:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void test()
{
    int a = 0;
    clock_t t1 = clock();
    for (int i = 0; i < 100000000; i++)
    {
        a = i + 1;
    }
    a = 0;
    for (int i = 0; i < 100000000; i++)
    {
    a = i + 1;
    }
    clock_t t2 = clock();
    printf("Time = %d\n", t2 - t1);
}

int main(int argc, char* argv[])
{
    clock_t t1 = clock();
    for (int j = 0; j < 8; j++)
    {
        test();
    }
    clock_t t2 = clock();
    printf("Normal operation total time = %d\n", t2 - t1);

    t1 = clock();
#pragma omp parallel for
    for (int j = 0; j < 8; j++)
    {
        test();
    }
    t2 = clock();
    printf("OpenMP operation total time = %d\n", t2 - t1);

    system("pause");
    return 0;
}

需要关注的代码是:

#pragma omp parallel for
for (int j = 0; j < 8; j++)
{
    test();
}

这一段代码是启用OpenMP进行并行运算,关键的指令也只有一句:

#pragma omp parallel for

这一句指令是用于指定其后面的一个for循环会被用于并行执行,并且,这句指令只对紧随其后的for循环起作用,不会对多个for循环起作用。上面这个例子中,虽然for循环部分是并行执行的,但是这个程序还是串行的,也就是并行部分没有执行完成,for循环后面的clock_t t2 = clock();以及之后的代码是不会被执行,这种并行方式是标准的并行模式fork/join式并行模式,这种模式创建的线程和主线程不是并行的。

春日宴,绿酒一杯歌一遍。再拜陈三愿:一愿郎君千岁,二愿妾身常健,三愿如同梁上燕,岁岁长相见。
– 冯延巳 《长命女》