博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
4、OpenMP的临界区critical、atomic、omp_lock_t
阅读量:4171 次
发布时间:2019-05-26

本文共 2216 字,大约阅读时间需要 7 分钟。

基本思想:OpenMP和多线程的互斥锁很像

#pragma omp parallel for    for(int i=0;i

测试代码 :critical 可以对代码块进行临界区设置,而atomic只能对代码语句进行加持

#include 
#include
#include
using namespace std;using namespace chrono;void sequentialProgram(int num){ int sum=0; int doubleI=0; for(int i=0;i
(end_time-start_time).count()<<" seconds"<
(end_time-start_time).count()<<" seconds"<

测试结果:发现不添加临界区,计算的值并不正确,因此在累加和累乘运算过程中,需要临界区的加持

F:\OpenMP\cmake-build-debug\OpenMP.exesum=14280sequentialProgram elapse time: 0.0004372 secondssum=13790sum=14280parallelProgram elapse time: 0.0023326 secondsProcess finished with exit code 0

如果将错误的代码注释掉,会发现临界区的执行时间还是长于串行求和的程序的,因此并不划算~ 具体方法参考reduction 

F:\OpenMP\cmake-build-debug\OpenMP.exesum=14280sequentialProgram elapse time: 0.0005795 secondssum=14280parallelProgram elapse time: 0.0031314 secondsProcess finished with exit code 0

(2)atomic 对代码语句进行临界设置

 atomic 只能针对单条语句线程互斥访问,它的使用和 #pragra omp parallel for 一样 只能直接接语句 不能在套一个大括号

测试代码

#include 
#include
#include
using namespace std;using namespace chrono;void sequentialProgram(int num){ int sum=0; int doubleI=0; for(int i=0;i
(end_time-start_time).count()<<" seconds"<
(end_time-start_time).count()<<" seconds"<

测试结果

F:\OpenMP\cmake-build-debug\OpenMP.exesum=14280sequentialProgram elapse time: 0.0005045 secondssum=14280parallelProgram elapse time: 0.0015284 secondsProcess finished with exit code 0

其中可以使用原子操作的运算符有 +、-、*、/、|、^、&、>>、<<

(3)添加锁

static omp_lock_t m_lock;omp_init_lock(&m_lock);#pragma omp parallel for    for(int i=0;i

测试代码

#include 
#include
#include
using namespace std;using namespace chrono;static omp_lock_t m_lock;void sequentialProgram(int num){ int sum=0; int doubleI=0; for(int i=0;i
(end_time-start_time).count()<<" seconds"<
(end_time-start_time).count()<<" seconds"<

测试结果 如果计算量很大的话,这样写会消耗的时间高于串行程序

F:\OpenMP\cmake-build-debug\OpenMP.exesum=14280sequentialProgram elapse time: 0.0341926 secondssum=14280parallelProgram elapse time: 0.0020649 secondsProcess finished with exit code 0

转载地址:http://ctyai.baihongyu.com/

你可能感兴趣的文章
计算Windows下目录大小
查看>>
python web框架企业实战详解(第六期)\第三课时-css&bootstrap
查看>>
python web框架企业实战详解(第六期)\第三课时-ajax&jquery&webpy
查看>>
python web框架企业实战详解(第六期)\第二课时-pickle&__eq__
查看>>
python web框架企业实战详解(第六期)\第一课时-sorted&if&for
查看>>
python web框架企业实战详解(第六期)\第四课时-webpy&django
查看>>
db2 - DETACH & ATTACH PARTITION
查看>>
How is map() implemented internally in Python?
查看>>
导出所有DB2存储过程的四种方法
查看>>
py - understanding zip function
查看>>
DB2 LOAD 工具使用技巧集合
查看>>
db2 - Partitioning on Multiple Columns
查看>>
db2 - 如何在shell中获取存储过程OUT型参数的返回值(awk)
查看>>
RANK() OVER(PARTITION BY deptno ORDER BY empno)
查看>>
Shell开发的一些技巧和经验
查看>>
C++内存问题(很多公司面试的题目,值得一看,看懂了别忘了告诉我)
查看>>
VBS递归遍历文件夹
查看>>
JCSetter.vbs(Java CLASSPATH Setter)
查看>>
Java中日期的使用
查看>>
VBA创建类事件
查看>>