3

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Maestro
  • 9,046
  • 15
  • 83
  • 116
  • 1
    You never had guaranteed atomic operations. http://stackoverflow.com/questions/1790204/in-c-is-i-1-atomic?rq=1 – Paul Hankin Feb 02 '13 at 13:13
  • An implementation doesn't just encompass the hardware, but also the operating system, the compiler and the standard library. As you've tagged "gcc", I would assume you're using an OS. Which documentation tells you about atomicity? Does your hardware agree with your OS, gcc and libgcc in regards to the definition of "atomic"? How does your hardware deal with reads/writes from different software-based threads that are running on the same core? – autistic Feb 02 '13 at 13:29
  • @Anonymous Your assumption is true generally speaking about C. But given a specific CPU and compiler, you may have a better knowledge on operation atomicity. Now this will drive to totally unportable code. – greydet Feb 02 '13 at 13:31
  • @modifiablelvalue No I'm not using an OS, it's an embedded system. – Maestro Feb 02 '13 at 13:46
  • @Joshua That response was only slightly relevant to one of the three questions I asked. Please read my last comment carefully and respond to all of the questions, citing from manuals regarding all aspects of your implementation (not just your hardware) where possible, so that I may help you... – autistic Feb 02 '13 at 13:51
  • 3
    Packed structs are not a valid technique to 'save memory'. You will get identical savings just ordering the members right so that padding is not needed. – R.. GitHub STOP HELPING ICE Feb 02 '13 at 14:54

1 Answers1

2

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.

greydet
  • 5,509
  • 3
  • 31
  • 51