简体   繁体   English

在C ++ 11和OpenMP中以原子方式访问非原子内存位置?

[英]Atomic access to non-atomic memory location in C++11 and OpenMP?

OpenMP, in contrast to C++11, works with atomicity from a perspective of memory operations, not variables. 与C ++ 11相比,OpenMP从内存操作而非变量的角度来看具有原子性。 That allows, eg, 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];

In C++11, this is not possible to achieve. 在C ++ 11中,这是不可能实现的。 We can kind-of access atomic variables as non-atomic by relaxing memory model, but we cannot resize a vector of atomic elements. 通过放松内存模型,我们可以将原子变量作为非原子访问,但是我们不能调整原子元素向量的大小。

I understand that there are reasons why C++ does not allow to access non-atomic variables by atomic memory operations. 我了解C ++不允许通过原子内存操作访问非原子变量的原因。 But I wonder, why these reasons do not apply for OpenMP as well. 但我想知道,为什么这些原因也不适用于OpenMP。

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." 例如,在N4013中 ,据说“没有合理的方法完全将原子操作可移植地应用于未声明为原子的数据。” How it's possible that OpenMP can guarantee such portability and C++ not? OpenMP如何保证这种可移植性而C ++不能保证这种可移植性?

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. 据我了解各自的标准,OpenMP的使用限制比C ++ 11更大,这使它无需使用特殊类型即可移植。 For example, OpenMP 4.5 says: 例如,OpenMP 4.5说:

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. 如果x所指定的存储位置不是大小对齐的(也就是说,如果x的字节对齐不是x大小的倍数),那么将定义实现原子区域的行为。

On the other hand, if C++11 uses std::atomic<int> , then the compiler will guarentee the appropriate alignment. 另一方面,如果C ++ 11使用std::atomic<int> ,则编译器将确保适当的对齐方式。 In both cases, alignment is required, but OpenMP and C++11 differ in who is responsible for ensuring this is done. 在这两种情况下,都需要对齐,但是OpenMP和C ++ 11在确保完成此操作的人员方面有所不同。

Generally, there are philosophical differences between OpenMP and C++, but it's hard to enumerate all of them. 通常,OpenMP和C ++之间在哲学上存在差异,但很难一一列举。 The C++ folks are thinking about portability to everything, whereas OpenMP is targeted at HPC. C ++人士正在考虑可移植性,而OpenMP则针对HPC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM