lundi 14 mai 2018

Is initializing a atomic pointer atomic? What happens if initialization or memory allocation throws?

If i declare and define a atomic pointer in one go like -

std::atomic<int*> iptr = new int(1);    
std::atomic<T*> iptr = new T();

As I understand the whole operation is not atomic.

new T() involves assigning memory, constructing the T object and then it will be atomically assigned to iptr. T may be trivially constructible in which case constructing T should not throw but some user defined T MAY throw.

What if in between T construction or memory assignment some other thread uses iptr?

Is this operation really atomic? One way to make it atomic is breaking the declaration and definition e.g.

T* temp = new T();
std::atomic<T*> iptr = temp;    

Is there any other way to do the same thing atomically? Is my understanding flawed?

Aucun commentaire:

Enregistrer un commentaire