一 OpenMP 教程 深入人剖析 OpenMP reduction 子句( 四 )

上面的程序输出结果如下所示:
data = https://www.huyubaike.com/biancheng/-2147483648 tid = 0data = -2147483648 tid = 1data = 1000可以看出程序被正确的初始化成最小值了,主函数当中输出的数据应该等于 max(1000, 10, 20) 因此也满足条件 。
& 按位与#include <stdio.h>#include <omp.h>static int data = https://www.huyubaike.com/biancheng/15;int main() {#pragma omp parallel num_threads(2) reduction(&:data){printf("data = https://www.huyubaike.com/biancheng/%d tid = %d/n", data, omp_get_thread_num());if(omp_get_thread_num() == 0) {data = https://www.huyubaike.com/biancheng/8;}else if(omp_get_thread_num() == 1){data = 12;}}printf("data = https://www.huyubaike.com/biancheng/%d/n", data);return 0;}上面的程序输出结果如下:
data = https://www.huyubaike.com/biancheng/-1 tid = 0data = -1 tid = 1data = 8首先我们需要知道上面几个数据的比特位表示:
-1 = 1111_1111_1111_1111_1111_1111_1111_11118= 0000_0000_0000_0000_0000_0000_0000_100012 = 0000_0000_0000_0000_0000_0000_0000_110015 = 0000_0000_0000_0000_0000_0000_0000_1111我们知道当我们使用 & 操作符的时候初始值是比特为全部等于 1 的数据,也就是 -1,最终进行按位与操作的数据为 15、8、12,即在主函数当中输出的结果等于(8 & 12 & 15) == 8,因为只有第四个比特位全部为 1,因此最终的结果等于 8。
|按位或#include <stdio.h>#include <omp.h>static int data = https://www.huyubaike.com/biancheng/1;int main() {#pragma omp parallel num_threads(2) reduction(|:data){printf("data = https://www.huyubaike.com/biancheng/%d tid = %d/n", data, omp_get_thread_num());if(omp_get_thread_num() == 0) {data = https://www.huyubaike.com/biancheng/8;}else if(omp_get_thread_num() == 1){data = 12;}}printf("data = https://www.huyubaike.com/biancheng/%d/n", data);return 0;}上面的程序输出结果如下所示:
data = https://www.huyubaike.com/biancheng/0 tid = 0data = 0 tid = 1data = 13我们还是需要了解一下上面的数据的比特位表示:
0= 0000_0000_0000_0000_0000_0000_0000_00001= 0000_0000_0000_0000_0000_0000_0000_00018= 0000_0000_0000_0000_0000_0000_0000_100012 = 0000_0000_0000_0000_0000_0000_0000_110013 = 0000_0000_0000_0000_0000_0000_0000_1101线程初始化的数据等于 0 ,这个和前面谈到的所有的比特位都设置成 0 是一致的,我们对上面的数据进行或操作之后得到的结果和对应的按位或得到的结果是相符的 。
^按位异或#include <stdio.h>#include <omp.h>static int data = https://www.huyubaike.com/biancheng/1;int main() {#pragma omp parallel num_threads(2) reduction(^:data){printf("data = https://www.huyubaike.com/biancheng/%d tid = %d/n", data, omp_get_thread_num());if(omp_get_thread_num() == 0) {data = https://www.huyubaike.com/biancheng/8;}else if(omp_get_thread_num() == 1){data = 12;}}printf("data = https://www.huyubaike.com/biancheng/%d/n", data);return 0;}上面的程序的输出结果如下所示:
data = https://www.huyubaike.com/biancheng/0 tid = 0data = 0 tid = 1data = 5各个数据的比特位表示:
0= 0000_0000_0000_0000_0000_0000_0000_00001= 0000_0000_0000_0000_0000_0000_0000_00018= 0000_0000_0000_0000_0000_0000_0000_100012 = 0000_0000_0000_0000_0000_0000_0000_11005= 0000_0000_0000_0000_0000_0000_0000_0101大家可以自己对照的进行异或操作,得到的结果是正确的 。
总结在本篇文章当中我们主要使用一个例子介绍了如何解决并发程序当中的竞争问题,然后也使用了 reduction 子句去解决这个问题,随后介绍了在 OpenMP 当中 reduction 各种规约符号的使用!
在本篇文章当中主要给大家介绍了 OpenMP 的基本使用和程序执行的基本原理,在后续的文章当中我们将仔细介绍各种

经验总结扩展阅读