Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to different offsets in array always well defined

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?

like image 590
Voo Avatar asked Jan 10 '16 14:01

Voo


1 Answers

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.

like image 149
Vaughn Cato Avatar answered Oct 12 '22 18:10

Vaughn Cato