I'm writing code for a Cortex M0 (ARM) CPU, and 32-bit reads/writes are atomic. Now I was wondering when I read/write 8bit/16bit variables, are they also guaranteed to be atomic? My instinct says yes, because they are internally aligned to 32-bit sections, so there is no possibility that the CPU needs two separate instructions to read/write them.
But I also happen to store a lot of variables in packed structures to save memory, and there it's possible that variables are not aligned on 32-bit boundaries, so each half of a 16-bit value could be in a different section.
So is it true that I lose atomic operations when I use packed structures?
Using packed structures you will never have read/write atomic operations on fields that overlaps a memory unit boundary. This means that only 8bits operations are guaranteed to be atomic, otherwise it depends on the memory alignment of your fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With