Writing to different offsets in array always well defined

随声附和 提交于 2019-12-08 17:16:53

问题


In this question it was brought up that writing to two different offsets in a char array concurrently would imply a data race, since some processors such as Alpha don't have byte-wise addressing so it'd be hard to implement this.

I certainly see that this would very much slow down writing bytes on alpha processors (basically involving a LL/SC), but as I understand the C++ standard every field in an array is its own memory location (although from reading §1.7, I could also see the whole array as one memory location - that's probably what this question boils down to).

So basically is the following pseudo code

char arr[10]; // global field
Thread 1:
arr[1] = 0;
Thread 2:
arr[0] = 1;

well defined according to the C++14 standard or not?


回答1:


From the C++14 standard (1.7/3):

Two or more threads of execution (1.10) can update and access separate memory locations without interfering with each other.

Where it previously defines (emphasis mine)

A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width.

So the chars of the array are memory locations, but the array itself is not; therefore, separate threads writing to different chars do not interfere with each other.



来源:https://stackoverflow.com/questions/34706564/writing-to-different-offsets-in-array-always-well-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!