user3217789
user3217789

Reputation: 211

Basic C++ atomic array

I am trying to use a basic array of objects using C++11 atomics, i.e. below:

// Atomic array
std::atomic<Object*> *array = new std::atomic<Object*>[10];

// Storing old data
array[0].store(oldObject);

// Store the new data
Object *newObject = new Object();
while(!array[0].compare_exchange_strong(oldObject,newObject)); 

My question is, can the CAS operation fail only if another thread is modifying the the array at the same index? Or will the CAS operation fail if any thread is trying to modify any location within the array? The latter is the behaviour that I seem to be getting during tests. If so, is there a better way to declare an array so that modifying different individual cells in the array don't effect each other?

Thanks.

Upvotes: 9

Views: 1610

Answers (1)

Douglas Leeder
Douglas Leeder

Reputation: 53310

IIRC atomic variables on a single cache-line will share the locking (on x86{,_64}).

So maybe extend the array and try variables at each end to test that?

Upvotes: 1

Related Questions