Atomic variable read and write

Hi,
if I use a 32 bit variable in a 32 bit micro is it 100% guaranteed that the reading and writing is done in a single cycle?
Or are there some cases and/or micros where that might not be the guaranteed case?

If relevant, the micro I am using is PIC32MZ

Thank you

Yes it should be atomic on a PIC32.

If the write to the variable is modify the existing value in some way (like adding 1 to it) then the operation will require a read/modify/write sequence. So in step 1 the MCU will read the 32-bit variable into a 32-bit register. In step 2 the MCU will update the variable (add 1 to it to keep the same example). Step 3 will write the new value back to memory (assuming compiler optimisation is not keeping it in a register - should make the variable volatile if it is accessed from multiple threads). But another thread reading the same variable at any point within those three operations will always read a consistent value back.

Thank you Richard,
slightly unclear about the step 3 you wrote “Step 3 will write the new value back to memory (assuming compiler optimisation is not keeping it in a register - should make the variable volatile if it is accessed from multiple threads).” Mainly because then in the last statement you mention “will always be a consistent value”.

Who should make the variable volatile? The RTOS by default through its internal workings or should I define it volatile?

And if that is not the case then the operation would not be atomic or would it still be?

Thank you

Ensuring that changes to a global variable are visible to all tasks/ISRs is done by declaring the variable volatile which is a C/C++ language keyword.
See the C/C++ standard (or google) for the explanation of that keyword.
That’s outside the scope of the OS and completely up to the compiler.
With more sophisticated CPU architectures volatile might be not sufficient and atomic datatypes should be used. See C11 _Atomic or C++ std::atomic.

Thank you Hartmut :slight_smile: