代码展示了基础的语法,没有涉及同步的问题:
#include <iostream>
#include"omp.h"
#include<stdio.h>
int main()
{
//parallel是让所有线程重复执行同样的任务,这里为了演示后面加omp_get_thread_num()来区分
printf("以下是parallel:\n");
#pragma omp parallel
{
printf( "Hello World! \t thread:%d \n",omp_get_thread_num());
//这里没有用cout是因为不同线程的执行速度有差异,对屏幕多次访问造成输出不连贯,显示不美观
}
int i = 0;
//for不经常用,以下示例也表明循环只有一个线程在执行,并且for后直接加循环,而非大括号
printf("以下是for:\n");
#pragma omp for
for (i=0;i<6;i++)
{
printf("Hello World! \t thread:%d \t time:%d \n", omp_get_thread_num(),i);
}
//parallel for是比较常用的,相当于parallel+for
//子句有多种schedule可以选择
printf("以下是parallel for:\n");
#pragma omp parallel for if(i>4)
for (i = 0; i < 10; i++)
{
printf("Hello World! \t thread:%d \t time:%d \n", omp_get_thread_num(), i);
}
//sections分区编程,每个独立分区用section表示
//分区编程更具有普适性,不局限于循环并且比较灵活
printf("以下是sections:\n");
int sum1=0, sum2=0;
#pragma omp parallel sections
{
#pragma omp section
for (int j = 1; j <= 10; j++)
sum1 = sum1 + j;
#pragma omp section
for (int k = 11; k <= 20; k++)
sum2 = sum2 + k;
}
printf("sum:%d \n",sum1+sum2);
}
程序执行结果如下:
以下是parallel:
Hello World! thread:0
Hello World! thread:1
Hello World! thread:2
Hello World! thread:3
以下是for:
Hello World! thread:0 time:0
Hello World! thread:0 time:1
Hello World! thread:0 time:2
Hello World! thread:0 time:3
Hello World! thread:0 time:4
Hello World! thread:0 time:5
以下是parallel for:
Hello World! thread:0 time:0
Hello World! thread:0 time:1
Hello World! thread:0 time:2
Hello World! thread:1 time:3
Hello World! thread:1 time:4
Hello World! thread:1 time:5
Hello World! thread:3 time:8
Hello World! thread:3 time:9
Hello World! thread:2 time:6
Hello World! thread:2 time:7
以下是sections:
sum:210