Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is pointer assignment atomic in C++?

I've actually heard claims both ways. I suspect they are not, but I wanted to get the topic settled.

like image 786
fbrereto Avatar asked Jan 19 '12 01:01

fbrereto


People also ask

Are assignments atomic in C?

In C and C++, every operation is presumed non-atomic unless otherwise specified by the compiler or hardware vendor – even plain 32-bit integer assignment. The language standards have nothing to say about atomicity in this case.

Is assignment an atomic operation?

Neither of them are, although it is quite rare for the assignment to not be atomic.

What is pointer assignment?

In ordinary assignment involving pointers, the pointer is an alias for its target. In pointer assignment, the pointer is associated with a target. If the target is undefined or disassociated, the pointer acquires the same status as the target.

Is pointer a CPP?

Pointers (C++) A pointer is a variable that stores the memory address of an object. Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions.


2 Answers

C++03 does not know about the existance of threads, therefore the concept of atomicity doesn't make much sense for C++03, meaning that it doesn't say anything about that.

C++11 does know about threads, but once again doesn't say anything about the atomicity of assigning pointers. However C++11 does contain std::atomic<T*>, which is guaranteed to be atomic.

Note that even if writing to a raw pointer is atomic on your platform the compiler is still free to move that assingment around, so that doesn't really buy you anything.

If you need to write to a pointer which is shared between threads use either std::atomic<T*> (or the not yet official boost::atomic<T*>, gccs atomic intrinsics or windows Interlocked*) or wrap all accesses to that pointer in mutexes.

like image 179
Grizzly Avatar answered Sep 28 '22 15:09

Grizzly


The C++ norm does not define specific threading behavior. Depending on the compiler and the platform, the pointer assignment may or may not be atomic.

like image 42
Frizlab Avatar answered Sep 28 '22 15:09

Frizlab