以原子方式访问C ++ 11和OpenMP中的非原子内存位置? [英] Atomic access to non-atomic memory location in C++11 and OpenMP?

查看:100
本文介绍了以原子方式访问C ++ 11和OpenMP中的非原子内存位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与C ++ 11相比,OpenMP从内存操作而非变量的角度来看具有原子性.例如,这允许在编译时对存储在未知大小的向量中的整数使用原子读取/写入:

OpenMP, in contrast to C++11, works with atomicity from a perspective of memory operations, not variables. That allows, e.g., to use atomic reads/writes for integers being stored in a vector with unknown size at compile time:

std::vector<int> v;

// non-atomic access (e.g., in a sequential region):
v.resize(n);
...
v.push_back(i);
...

// atomic access in a multi-threaded region:
#pragma omp atomic write // seq_cst
v[k] = ...;
#pragma omp atomic read // seq_cst
... = v[k];

在C ++ 11中,这是不可能实现的.通过放松记忆模型,我们可以将原子变量作为非原子访问,但是我们不能调整原子元素的向量的大小.

In C++11, this is not possible to achieve. We can kind-of access atomic variables as non-atomic by relaxing memory model, but we cannot resize a vector of atomic elements.

我了解C ++不允许通过原子内存操作访问非原子变量的原因.但是我想知道,为什么这些原因也不适用于OpenMP.

I understand that there are reasons why C++ does not allow to access non-atomic variables by atomic memory operations. But I wonder, why these reasons do not apply for OpenMP as well.

例如,在 N4013 ,据说没有合理的方法完全将原子操作可移植地应用到未声明为原子的数据上." OpenMP如何保证这种可移植性,而C ++不能呢?

For example, in N4013, it is said that "There is no reasonable way to completely portably apply atomic operations to data not declared as atomic." How it's possible that OpenMP can guarantee such portability and C++ not?

推荐答案

据我了解各自的标准,OpenMP比C ++ 11在使用上有更多限制,这使其可以在不使用特殊类型的情况下进行移植.例如,OpenMP 4.5表示:

As far as I understand the respective standards, OpenMP has more restrictions on usage than C++11, which allows it to be portable without using special types. For example, OpenMP 4.5 says:

如果x所指定的存储位置不是大小对齐的(即,如果x的字节对齐不是x大小的倍数),那么将定义实现的原子区域行为.

If the storage location designated by x is not size-aligned (that is, if the byte alignment of x is not a multiple of the size of x), then the behavior of the atomic region is implementation defined.

另一方面,如果C ++ 11使用std::atomic<int>,则编译器将确保适当的对齐方式.在这两种情况下,都需要对齐,但是OpenMP和C ++ 11在确保完成此任务的人员方面有所不同.

On the other hand, if C++11 uses std::atomic<int>, then the compiler will guarentee the appropriate alignment. In both cases, alignment is required, but OpenMP and C++11 differ in who is responsible for ensuring this is done.

通常,OpenMP和C ++之间在哲学上存在差异,但是很难一一列举. C ++人士正在考虑可移植到一切的问题,而OpenMP是针对HPC的.

Generally, there are philosophical differences between OpenMP and C++, but it's hard to enumerate all of them. The C++ folks are thinking about portability to everything, whereas OpenMP is targeted at HPC.

这篇关于以原子方式访问C ++ 11和OpenMP中的非原子内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆