openmp 处理数据竞争的问题 reduction

文章对比了两个C++代码示例,一个是使用OpenMP的多线程计算中未使用reduction导致的竞争问题,另一个通过reduction实现了线程安全的累加操作,解释了如何利用单位元和结合律提高效率。

类似 多线程竞争,需要加锁来保护类似,但实现原理不同,reduction 并不会像多线程原子操作那样影响效率,因为它使用了高等代数里的单位元和结合律思想,为每个线程定义一个单位元,开始 分段积累运算操作。

1, 不可避免竞争的示例

hello_without_reduction.cpp

#include <omp.h>
#include <math.h>
#include <iostream>

int main()
{
        float sum = 0;

        omp_set_num_threads(4);
        #pragma omp parallel
        {
                #pragma omp for
                for(int i=0; i<17; i++){
                        sum += cos(i) + sin(i);
                        //printf("%d , th=%d\n", i, omp_get_thread_num());
                }
        }
        std::cout<< sum <<std::endl;

}

_______
Makefile:

CXX:=g++


hello_nr: hello_without_reduction.o
        ${CXX} -o $@  $< -fopenmp
        #${CXX} -o $@ -fopenmp $<

hello_without_reduction.o: hello_without_reduction.cpp
        ${CXX} -c -o $@  $< -fopenmp

.PHONY:clean
clean:
        -rm -f hello_without_reduction hello_without_reduction.o

出错效果:

2,避免了竞争的示例


hello_with_reduction.cpp
 

#include <omp.h>
#include <math.h>
#include <iostream>

int main()
{
        float sum = 0;

        omp_set_num_threads(4);
        #pragma omp parallel
        {
                #pragma omp for reduction(+:sum)
                for(int i=0; i<17; i++){
                        sum += cos(i) + sin(i);
                        //printf("%d , th=%d\n", i, omp_get_thread_num());
                }
        }
        std::cout<< sum <<std::endl;

}

_______________________________________________________________
Makefile:

CXX:=g++


hello_nr: hello_with_reduction.o
        ${CXX} -o $@  $< -fopenmp
        #${CXX} -o $@ -fopenmp $<

hello_with_reduction.o: hello_with_reduction.cpp
        ${CXX} -c -o $@  $< -fopenmp

.PHONY:clean
clean:
        -rm -f hello_with_reduction hello_with_reduction.o

无错效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值