camino
camino

Reputation: 10574

Is it thread safe to write different item of c array in multiple threads in c++?

suppose we have an array

int a[2];

thread 1 only write/read a[0]

thread 2 only write/read a[1]

Is this thread safe?

Upvotes: 4

Views: 190

Answers (2)

KABoissonneault
KABoissonneault

Reputation: 2369

From the standard's [intro.memory#3]

A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having nonzero width. [...] Two or more threads of execution can access separate memory locations without interfering with each other.

int is such a scalar type, and therefore each element of the array is its own memory location, meaning multiple threads of execution can access each of them separately without interference.

Upvotes: 3

user2100815
user2100815

Reputation:

Yes, it is safe, in the same way that accessing two different int variables would be safe.

Upvotes: 1

Related Questions