mardi 1 mai 2018

Interlocked functions and atomicity: still confused

I'm still confused about reading and writing variables atomically. So sorry in advance to those who have tried to help in previous questions.

I have been told today that there is no need for any Interlocked function call when reading and writing a 32bit long value, which blows my previous beliefs out of the window. Indeed, this backs up what MSDN says

Simple reads and writes to properly-aligned 32-bit variables are atomic operations. In other words, you will not end up with only one portion of the variable updated; all bits are updated in an atomic fashion

So I then looked at what atomic_long in VS2017 does; its operator= does an _InterlockedExchange() on the current value with the new value.

1)

Doesn't this contradict MSDN; if the read/write is atomic, why is this Interlocked function needed?

On the same MSDN page, we also have

Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.

So I then step into atomic_bool's 'operator=; it executes a _InterlockedExchange8 call which MSDN tells me is only available on Windows 8 and above.

This seems to back up the second MSDN quote.

2)

If I am using VS 2005 and targeting Windows XP, how would I ensure an atomic read/write of a boolean variable? Would I have to use a mutex or similar?

3)

If a read/write operation is not atomic, that leaves it susceptible to being torn; is that correct?

4)

I have read this PAQ that says primitive types are not atomic. Again this contradicts what I have been told in my questions and what MSDN has told me. Who is correct?

I hope this doesn't offend anyone but as a beginner to all this I'm finding it quite unpleasant with all this contradicting information.

Aucun commentaire:

Enregistrer un commentaire