Is changing a pointer considered an atomic action in C?

Andrioid picture Andrioid · May 18, 2009 · Viewed 12k times · Source

If I have a multi-threaded program that reads a cache-type memory by reference. Can I change this pointer by the main thread without risking any of the other threads reading unexpected values.

As I see it, if the change is atomic the other threads will either read the older value or the newer value; never random memory (or null pointers), right?

I am aware that I should probably use synchronisation methods anyway, but I'm still curious.

Are pointer changes atomic?

Update: My platform is 64-bit Linux (2.6.29), although I'd like a cross-platform answer as well :)

Answer

Michael picture Michael · May 18, 2009

As others have mentioned, there is nothing in the C language that guarantees this, and it is dependent on your platform.

On most contemporary desktop platforms, the read/write to a word-sized, aligned location will be atomic. But that really doesn't solve your problem, due to processor and compiler re-ordering of reads and writes.

For example, the following code is broken:

Thread A:

DoWork();
workDone = 1;

Thread B:

while(workDone != 0);

ReceiveResultsOfWork();

Although the write to workDone is atomic, on many systems there is no guarantee by the processor that the write to workDone will be visible to other processors before writes done via DoWork() are visible. The compiler may also be free to re-order the write to workDone to before the call to DoWork(). In both cases, ReceiveResultsOfWork() might start working on incomplete data.

Depending on your platform, you may need to insert memory fences and so on to ensure proper ordering. This can be very tricky to get right.

Or just use locks. Much simpler, much easier to verify as correct, and in most cases more than performant enough.