14

On ARM architecture, unfortunately I don't know exactly what chip it is, is a 32 bit int read/write atomic?

Is there any sort of guarantees about reads/writes to basic types?

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • If that `int` is suitably aligned (to 4 bytes), I guess that, like on most 32 bits processors, the write is somehow atomic. However, the real question is the memory model (notably in multi-core situations : cache coherency, etc.). – Basile Starynkevitch Feb 22 '12 at 16:41
  • Even in if there is no cache coherency, the read/write to main memory would still be atomic (but delayed) – Johan Kotlinski Feb 22 '12 at 16:42
  • @BasileStarynkevitch yes memory model is a good point, but I only have on ARM cpu with one core. – Tony The Lion Feb 22 '12 at 16:43
  • Yes, it is atomic (except perhaps in a packed struct). See my full answer, including for all other data types, here: https://stackoverflow.com/a/52785864/4561887. – Gabriel Staples Oct 29 '18 at 22:31

1 Answers1

12

It should be atomic, EXCEPT if that int is stored on a non-aligned address.

Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101
  • How does one find out if it's stored on a non-aligned address? I didn't do any special aligning. – Tony The Lion Feb 22 '12 at 16:42
  • 2
    Check whether its address mod 4 is 0. Although if you didn't do anything weird (type-punning, etc.), then the compiler's going to make it aligned. – jjlin Feb 22 '12 at 16:49
  • 3
    Actually some ARM processors like the Cortex-M3 support unaligned access in HW, so even an unaligned read/write is atomic. The access may span multiple bus cycles to memory, but there is no opportunity for another instruction to jump inbetween, so it is atomic to the programmer. – TJD Feb 22 '12 at 16:52
  • 2
    Last I checked ARM does not support unaligned access. In any case this question is tagged C and unaligned access is illegal C (undefined behavior). – R.. GitHub STOP HELPING ICE Feb 22 '12 at 17:41
  • @TonyTheLion: The only ways an `int` can come into existence in C all necessitate that it's on an aligned address. The only way it wouldn't be is if you illegally try to access some memory that's not an `int` as if it were. – R.. GitHub STOP HELPING ICE Feb 22 '12 at 17:47
  • 2
    @TJD, you're ignoring shared memory between processors/cores. Another processor might change the data while the current processor is connecting the parts. – ugoren Feb 22 '12 at 20:58
  • 1
    @TonyTheLion What about packed structures? – Guido Jul 11 '14 at 15:03